Python:动态定义函数 [英] Python: defining functions on the fly
问题描述
我有以下代码:
funcs = []
for i in range(10):
def func():
print i
funcs.append(func)
for f in funcs:
f()
问题是func
被覆盖.即代码的输出是:
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)
推荐答案
问题不在于func被覆盖,而是i
的值是在调用函数时(而不是在定义函数时)进行求值的.如果要在定义时评估i
,请将其作为默认参数作为func
放在函数声明中.
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 evaluate i
at definition time, put it in the function declaration, as a default argument to func
.
funcs = []
for i in range(10):
def func(value=i):
print value
funcs.append(func)
for f in funcs:
f()
在定义函数时,默认参数将被评估一次,因此递增循环不会影响它们.如果您使用过,效果会一样好
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
def func(i=i):
print i
但是我使用名称value
来明确函数中使用的名称.
but I used the name value
to make it clear which name is being used within the function.
这篇关于Python:动态定义函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!