溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

生成器和面向編程

發(fā)布時間:2020-07-28 07:48:12 來源:網(wǎng)絡(luò) 閱讀:282 作者:期待美好 欄目:編程語言
            生成器
只要在函數(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')
向AI問一下細節(jié)
AI