python異常與產生器

來源:互聯網
上載者:User

標籤:喚醒   func   print   font   while   ret   bsp   time   消費   

清單產生器:

[ i*2 for i in range(10) ]這不是是產生器

[ func(i) for i in range(10) ]

( i*2 for i in range(10) ) 這就是產生器

 

一個演算法,一個函數,可以邊迴圈邊產生資料,為了省空間,只有調用才會產生相應的資料。

只有__next()__方法

也可以用函數做個產生器

def fib(max):
    n,a,b = 0,0,1
    while n < max:
        print(b)
        a,b = b,a+b
        n = n + 1
    return ‘done‘
fib(10)


def fib(max):
    n,a,b = 0,0,1
    while n < max:
        yield(b)
        a,b = b,a+b
        n = n + 1
    return ‘done‘
print(fib(10))

fib_gen = fib(100)
print(fib_gen.__next__())
print(fib_gen.__next__())
print(fib_gen.__next__())

異常的捕獲

def fib(max):
n,a,b = 0,0,1
while n < max:
yield(b)
a,b = b,a+b
n = n + 1
return ‘done‘
print(fib(10))

fib_gen = fib(10)
print(fib_gen.__next__())
print(fib_gen.__next__())
print(fib_gen.__next__())
print(fib_gen.__next__())
print(fib_gen.__next__())
print(fib_gen.__next__())
print(fib_gen.__next__())
print(fib_gen.__next__())
print(fib_gen.__next__())
while True:
try:
print(fib_gen.__next__())
except StopIteration as e:
print("Generator return value:",e.value)
break

也可以這樣

def fib(max):
n,a,b = 0,0,1
while n < max:
yield(b)
a,b = b,a+b
n = n + 1
return ‘done‘
print(fib(10))

fib_gen = fib(10)

while True:
try:
print(fib_gen.__next__())
except StopIteration as e:
print("Generator return value:",e.value)
break

 

生產者與消費者

import time
def consumer(name):
print("%s準備吃包子"%name)
while True:
baozi = yield
print("包子[%s]來了,被[%s]吃了!"%(baozi,name))

c = consumer("Roger")
c.__next__();
baozi = "肉包子"
c.send(baozi)

send喚醒generator且給yield發送指
__next()只是喚醒generator,走到yield處,中斷,返回
繼續
import time
def consumer(name):
print("%s準備吃包子"%name)
while True:
baozi = yield
print("包子[%s]來了,被[%s]吃了!"%(baozi,name))

c = consumer("Roger")
c.__next__();
baozi = "肉包子"
c.send(baozi)
def producer(name):
c = consumer(‘A‘)
c2 = consumer(‘B‘)
c.__next__()
c2.__next__()
print("我開始準備做包子啦")
for i in range(10):
time.sleep(1)
print("做了2個包子")
c.send(i)
c2.send(i)
producer("alex")

產生器可以實現,單線程下的並行效果

攜程

 

 

  

 

python異常與產生器

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.