Python:动态定义函数
我有以下代码:
funcs = []
for i in range(10):
def func():
print i
funcs.append(func)
for f in funcs:
f()
问题是 func
被覆盖。即代码的输出是:
9
9
9
...
如果不定义新函数,您将如何解决这个问题?
最佳解决方案是更改函数的名称。即:(
for i in range(10):
def func+i():
...
或其他一些奇怪的语法)
I have the following code:
funcs = []
for i in range(10):
def func():
print i
funcs.append(func)
for f in funcs:
f()
The problem is that func
is being overriden. Ie the output of the code is:
9
9
9
...
How would you solve this without defining new functions?
The optimal solution would be to change the name of the function. Ie:
for i in range(10):
def func+i():
...
(or some other weird syntax)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
问题不在于 func 被覆盖,而在于调用函数时而不是定义函数时计算 i 的值。如果您想在定义时计算
i
,请将其放在函数声明中,作为func
的默认参数。默认参数在定义函数时计算一次,因此递增循环不会影响它们。如果您使用,这也同样有效,
但我使用名称
value
来明确函数中使用的名称。The problem is not that func is being overwritten, it's that the value of
i
is being evaluated when the function is called, not when it is defined. If you want to evaluatei
at definition time, put it in the function declaration, as a default argument tofunc
.Default arguments are evaluated once, when the function is defined, so the incrementing loop will not affect them. This would work just as well if you used
but I used the name
value
to make it clear which name is being used within the function.从另一个函数返回
func
最安全。Returning
func
from another function is safest.你可以尝试
You could try