生成器
只要在函數(shù)體內(nèi)出現(xiàn)yield關(guān)鍵字,那么再執(zhí)行函數(shù)就不會(huì)執(zhí)行函數(shù)代碼,會(huì)得到一個(gè)結(jié)果,該結(jié)果就是生成器。
生成器就是迭代器。
def foo():
print('add')
yield 1
print('sidhi')
yield 2
g=foo()
next(g)
res1=next(g)
print(res1)
yield的功能:
1.yield為我們提供了一種自定義迭代器對(duì)象的方法。
2.yield與retuen的區(qū)別,yield可以返回多次值,所以函數(shù)的暫停與繼續(xù)的轉(zhuǎn)態(tài)由yield幫我們保存的。
例:range的編寫 #range(1,10,2)
def bar(x,y,z):
while x <= y:
yield x
x+=z
g=bar(1,10,2)
print(next(g))
案例:編寫tail -f error.log |grep 'abc'
import time
def foo(file):
with open(file,'rb') as f:
f.seek(0,2) #光標(biāo)直接到末尾
while Ture:
line=f.readline() #.readline()每次只讀一行
if line:
yield line
else:
time.sleep(0.03)
def grep(line,pater):
for i in line:
i=i.decode('utf-8')
if pater in i:
yield i
g=grep(foo('error.log'),'abc')
for i in g:
print(i)
yiled表達(dá)式形式的用法:
def foo():
print('%s is pig' %name)
while Ture:
bar=yield #bar=yield='1111'
print('%s is pig %s' %(name,bar))
g=foo('abc')
netx(g) #初始化,也可以使用g.send(None)
然后g.send(),從代碼執(zhí)行到暫停的位置再將值傳給yield ,與next一樣。
g.send('1111')
g.send('2222')
面向過程編程: 過程指的是解決問題的步驟,即先設(shè)計(jì)框架,基于該思路編寫程序,是一種機(jī)械式方式。
優(yōu)點(diǎn):復(fù)雜問題流程化,進(jìn)而簡單化。
缺點(diǎn):可擴(kuò)展性差
案例:編寫grep -rl 'python' /etc
import os
def init(funce):
def titi(*args,**kawrgs):
g=funce(*args,**kawrgs)
next(g)
return g
return titi
@init #foo=titi
def foo(targrt):
while Ture:
path_a=yield
g=os.wal(path_a) #絕對(duì)路徑模塊
for a,b,c in g:
for c1 in c:
abc_path=r'%s/%s ' %s(a,c)
targrt.send(abc_path)
@init
def opener(targrt):
while Ture:
abc_path=yield
with open(abc_path,'rb') as f:
targrt.send(abc_path,f)
@init
def cat(targrt):
while Ture:
abc_path,f=yield
for line in f:
res=targrt.send((abc_path,line))
if res:
break
@init
def grep(targrt,pate):
pate=pate.encode('utf-8')
res=False
while Ture:
abc_path,line=yield res
res=False
if pate in line:
res=Ture
targrt.send(abc_path)
@init
def printer():
while Ture:
abc_path=yield
print('%s' %abc_path)
g=foo(opener(cat(grep(printer(),'python'))))
g.send(r'/home')
網(wǎng)站標(biāo)題:生成器和面向編程
鏈接地址:
http://weahome.cn/article/giighc.html