您好,登錄后才能下訂單哦!
生成器
只要在函數(shù)體內(nèi)出現(xiàn)yield關(guān)鍵字,那么再執(zhí)行函數(shù)就不會執(zhí)行函數(shù)代碼,會得到一個結(jié)果,該結(jié)果就是生成器。
生成器就是迭代器。
def foo():
print('add')
yield 1
print('sidhi')
yield 2
g=foo()
next(g)
res1=next(g)
print(res1)
yield的功能:
1.yield為我們提供了一種自定義迭代器對象的方法。
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) #光標直接到末尾
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表達式形式的用法:
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è)計框架,基于該思路編寫程序,是一種機械式方式。
優(yōu)點:復(fù)雜問題流程化,進而簡單化。
缺點:可擴展性差
案例:編寫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) #絕對路徑模塊
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')
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。