du3*_*369 14 python generator callable
生成器只是一个函数,它返回一个可以在其上调用的对象,这样每次调用它都会返回一些值,直到它引发一个StopIteration异常,表示已生成所有值.这样的对象称为迭代器.
>>> def myGen(n):
... yield n
... yield n + 1
...
>>> g = myGen(6)
Run Code Online (Sandbox Code Playgroud)
我从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
Run Code Online (Sandbox Code Playgroud)因此,根据<1>
和<2>
,g
's类型是'生成器',它不可调用.但是生成器是可调用的,调用生成器会获得一个迭代器对象
这里发生了什么?
当我在寻找答案时,我会遇到每次定义函数时python都会创建一个可调用对象.
那么,我可以这样说吗?定义函数时myGen
,myGen
是一个引用可调用对象的名称,该对象是具有__call__
方法的类的实例.在这种情况下,myGen
是一个生成器,并且myGen(6)
在myGen
被调用时是返回的迭代器.
但为什么要type(g)
回归<type 'generator'>
呢?这个返回的iterator
东西对我来说也很可疑,因为return
函数中没有声明.
归档时间: |
|
查看次数: |
3152 次 |
最近记录: |