动态调用函数和生成函数(python) [英] dynamic call of functions and generator function (python)

查看:241
本文介绍了动态调用函数和生成函数(python)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码只打印好。为什么生成器函数不执行?
我注意到pdb,执行'handlers1'后,脚本到达与f1的定义的行,但是不在函数内。相反,它返回'GeneratorExit:None'。

The following code only prints "good". Why the generator function is not executed? I noticed with pdb that after executing 'handlers1' the script reaches the line with f1's definition but then does not get inside the function. Conversely, it's returned '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()



Why this happens? Is it possible to call generator functions in a similar dynamic way?

推荐答案

您需要调用 / code>或生成器中的代码根本不会运行。

You need to call next or the code in the generator won't run at all.

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()

打印好然后不好。

这篇关于动态调用函数和生成函数(python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆