下面的代码只打印“good”。为什么不执行生成器功能? 我在pdb中注意到,在执行'handlers1'之后,脚本到达了f1定义的行,但是没有进入函数内部。相反,GeneratorExit返回了None。在
class foo:
def f0(self, s):
print s
def f1(self, s):
print "not " + s
yield 1
def run(self):
handlers={0 : self.f0, 1 : self.f1}
handlers[0]('good')
handlers[1]('good')
bar = foo()
bar.run()
为什么会这样?是否可以以类似的动态方式调用生成器函数?在
调用生成器函数的方式与调用普通函数的方式不同。生成器函数在调用时不运行,而是返回迭代器。当传递给
next()
或在其他迭代上下文中使用时,此迭代器将调用原始函数:要在另一个答案中继续讨论,下面是一种调用常规函数或生成器函数的方法:
^{pr2}$已调用生成器函数,但调用生成器函数不会立即执行任何操作。阅读the documentation,其中解释:
您需要调用
next
,否则生成器中的代码根本无法运行。在印的是“好”然后是“不好”。在
相关问题 更多 >
编程相关推荐