生成器:利用有順序或者遞歸的數列,列表,數組形成的函數,並能逐級往下打印,這是我理解的生成器。
圖片中的參數g就是一個生成器generator,對應着計算機的排序的在編碼的0x7f***
每次使用一次next函數就生成一個結果。
只要是一個生成器,我們就可以用for循環對着每個生成的結果取參,在將結果打印出來。(同時for循環也是驗證生成器方法))
生成器的兩種使用方法:
實例:演示利用生成器的方法傳送參數給函數,在打印輸出
[root@localhost 十九天]# cat test05.py #創建一個文件。
def gen(times):
n=0
while n < times:
temp=yield n*3
print(temp)
n=n+1
return "done"
[root@localhost 十九天]# ipython3 #啓動ipython3編輯器,將模塊導入測試。
/usr/python-3.4.6/lib/python3.4/site-packages/IPython/core/history.py:226: UserWarning: IPython History saved
warn("IPython History requires SQLite, your history will not be saved")
Python 3.4.6 (default, Jan 24 2019, 11:20:45)
Type 'copyright', 'credits' or 'license' for more information
IPython 6.5.0 -- An enhanced Interactive Python. Type '?' for help.
In [1]: from test05 import *
In [2]: g=gen(5) #將生成器賦予變量g
In [3]: g.send(None)#使用生成器的方法1
Out[3]: 0
In [4]: g.send("heh") #使用生成器的方法2,注意第一次傳參數是系統不支持,有興趣同學可以試一試;必須先傳其他參數才能用Send方法。
heh
Out[4]: 3
In [5]: globles
總結:生成器好比有個遞歸序列賦予一個變量中,每次可以使用這個變量的__init__方法,或者是x.send(*)方法。