欧美一区二区三区老妇人-欧美做爰猛烈大尺度电-99久久夜色精品国产亚洲a-亚洲福利视频一区二区

生成器和面向編程

            生成器
只要在函數(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)點:復雜問題流程化,進而簡單化。
缺點:可擴展性差

案例:編寫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')

當前標題:生成器和面向編程
文章路徑:http://chinadenli.net/article42/giighc.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供Google、移動網(wǎng)站建設(shè)微信公眾號、網(wǎng)站制作、全網(wǎng)營銷推廣電子商務(wù)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

外貿(mào)網(wǎng)站制作