以下代码只打印“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()
或在其他迭代上下文中使用时会调用原始函数:
>>> def f1(s):
... print(s)
... yield
...
>>> it = f1("hello")
>>> next(it)
hello
>>>
为了跟进另一个答案中的讨论,这里有一种调用常规函数或生成器函数的方法:
>>> def f0(s):
... print s
...
>>> def f1(s):
... print s
... yield
...
>>> try: next(f0("hello"))
... except TypeError: pass
...
hello
>>> try: next(f1("hello"))
... except TypeError: pass
...
hello
>>>
关于python - 函数和生成器函数的动态调用(python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18777544/