函数和生成器函数的动态调用(python)

2024-10-02 00:37:22 发布

您现在位置:Python中文网/ 问答频道 /正文

下面的代码只打印“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()

为什么会这样?是否可以以类似的动态方式调用生成器函数?在


Tags: 函数run代码self功能foohandlersdef
3条回答

调用生成器函数的方式与调用普通函数的方式不同。生成器函数在调用时不运行,而是返回迭代器。当传递给next()或在其他迭代上下文中使用时,此迭代器将调用原始函数:

>>> def f1(s):
...   print(s)
...   yield
... 
>>> it = f1("hello")
>>> next(it)
hello
>>> 

要在另一个答案中继续讨论,下面是一种调用常规函数或生成器函数的方法:

^{pr2}$

已调用生成器函数,但调用生成器函数不会立即执行任何操作。阅读the documentation,其中解释:

When a generator function is called, the actual arguments are bound to function-local formal argument names in the usual way, but no code in the body of the function is executed.

您需要调用next,否则生成器中的代码根本无法运行。在

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').next()

bar = foo()
bar.run()

印的是“好”然后是“不好”。在

相关问题 更多 >

    热门问题