[英]Is a generator the callable? Which is the generator?
生成器只是一個函數,它返回一個可以在其上調用的對象,這樣每次調用它都會返回一些值,直到它引發一個StopIteration異常,表示已生成所有值。 這樣的對象稱為迭代器。
>>> def myGen(n):
... yield n
... yield n + 1
...
>>> g = myGen(6)
我從Python中理解生成器中引用了這個?
這是我想弄清楚的:
哪個是發電機? myGen
或myGen(6)
?
根據上面提到的報價,我認為發電機應該是myGen
。 而myGen(6)
是返回的迭代器對象。 但我真的不確定。
當我嘗試這個時:
>>> type(myGen) <type 'function'> >>> type(g) # <1>this is confusing me. <type 'generator'> >>> callable(g) # <2> g is not callable. False >>> callable(myGen) True >>> g is iter(g) # <3> so g should an iterable and an iterator True # at the same time. And it will be passed as an argument >>> for i in g: # to built-in function `next()` in a "for...in..." loop. print i # (is that correct?) 6 7
因此,根據<1>
和<2>
, g
的類型是'generator',它不可調用。 但是生成器是可調用的,調用生成器會獲得一個迭代器對象這里發生了什么?
當我在尋找答案時,我會遇到每次定義函數時python都會創建一個可調用對象。
那么,我可以這樣說嗎? 當定義函數myGen
時, myGen
是一個引用可調用對象的名稱,該對象是具有__call__
方法的類的實例 。 在這種情況下, myGen
是一個生成器, myGen(6)
是調用myGen
時返回的迭代器。
但是為什么type(g)
返回<type 'generator'>
呢? 這個返回的iterator
對我來說也很可疑,因為函數中沒有return
語句。
1) myGen
是一個函數,當被調用時返回一個生成器對象 - 所以是的, myGen(6)
是一個生成器對象。
2)生成器提供__iter__
和next()
: docs
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.