dynamic call of functions and generator function (python)
以下代码只打印"良好"。为什么不执行生成器功能?我注意到在pdb中,在执行"handlers1"之后,脚本到达了f1定义的行,但随后没有进入函数。相反,它返回"generatorexit:none"。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 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() |
为什么会这样?是否可以以类似的动态方式调用生成器函数?
(P)只有一种方式不涉及同一个发电厂的正常功能。a Generatior function,when invoked,does not run but inside returns an iterator.This iterator,when passed to EDOCX1 university 0 or used in other iteration context,invokes the original function:(p)字母名称(P)To follow up on the discussion in another answer,here is a way to invoke either a regular function or a generatior function:(p)字母名称
(P)你需要在所有人都不会跑的时候叫一个字母或密码(p)字母名称(P)那些"好"的头条"不好"的头条(p)
(P)The generatior function is called,but calling a generatior function doesn't immediately do anything.Read the Documentation,which explains:(p)布尔奇1
(P)当你厌倦了一个世代的功能,它只是返回一个迭代。你应该Try to call the generatior's next method to execute the body of generatior function.Try this:(p)字母名称