Python學習筆記之函式生成器

2021-06-08 22:57:42 字數 1320 閱讀 2720

下面以乙個例子來說明生成器的呼叫執行過程,以及通過send(),close()介面與生成器進行通訊。

>>> def counter(start_at = 0):

count = start_at

while true:

val = (yield count) #1 返回count當前值,並暫停執行直到下次呼叫next()或send()

print 'yield count = ', count #2 輸出count的當前值

print 'yield val = ', val #3 輸出接受到的通過介面send()傳送的值,呼叫next()時為none

if val is not none: #4 如已呼叫send()介面,則處理接收到的值

print 'val = ', val

print 'count = ', count

count = val

else:

count += 1 #5 count加1,重新回到#1處執行

>>> count = counter(10)

>>> count.next()

10 #1 從#1處第一次返回count的初始值

>>> count.next() #1 繼續從#1處接著往下執行

yield count = 10 #2 輸出count當前值

yield val = none #3 沒有send()呼叫

11 #5#1 #5處已更新count的值,並在#1處返回

>>> count.send(20) #1 我們呼叫send()傳送資料20,程式從#1處繼續執行,但接受到send值20

yield count = 11

yield val = 20 # 接受到20的值

val = 20

count = 11

20>>> count.next()

yield count = 20

yield val = none

21>>> count.close() # 關閉迭代器,迭代器結束

>>> count.next() # 迭代器已結束,產生stopineration異常

traceback (most recent call last):

file "", line 1, in count.next()

stopiteration

>>>

Python學習筆記 Python之函式

1.函式引數函式定義的時候自己定義的引數,稱為形參 函式呼叫時候,其引數為實參,即實際要傳遞的引數 舉例 def pname username username 形參 print username pname python 傳遞了乙個實參 args是接受所有未命名的引數 關鍵字 是乙個元組型別 ag...

Python學習筆記 Python之函式

1.函式引數函式定義時,自己定義的引數,稱為形參 函式呼叫時,其引數為實參,即實際要傳遞的引數 舉例 def pname username username 形參 print username pname python 傳遞了乙個實參 args是接受所有未命名的引數 關鍵字 是乙個元組型別 agrs...

Python學習筆記之函式

python學習過程中重要的知識點函式。1.函式的定義 使用關鍵字 def def sayhello print hello word 以上函式功能只是做了簡單的螢幕輸出 2.函式呼叫 函式定義完之後,需要顯示呼叫才能執行函式體裡的 sayhello 在顯示的呼叫了sayhello 函式的時候,在螢...