每次调用函数时,如何计算Python函数的默认值? 拿这个虚拟代码:
b=0
def a():
global b
return b
def c(d=a()):
return d
我期望输出:
>>> c()
0
>>> b=1
>>> a()
1
>>> c()
1
我真正得到的是:
>>> c()
0
>>> b=1
>>> a()
1
>>> c()
0
答案 0 :(得分:3)
另一种解决方案,与您原来的答案更为相似。
b = 0
def a():
return b
def c(d=a): # When it's a parameter, the call will be evaluated and its return
# value will be used. Instead, just use the function name, because
return d() # within the scope of the function, the call will be evaluated every time.
当函数名称与括号及其参数(如f(x)
)配对时,假设您打算在此时调用它
答案 1 :(得分:1)
d = a()在程序开始进行计算(即a()在返回0时被调用...)
def c(d=None):
if d == None: d=a()
return d
将导致在您想要的时间进行评估
答案 2 :(得分:1)
这里的问题是,正如您可能已经知道的那样,在定义函数时会评估d=a()
(默认参数分配)。
要改变这种情况,使用例如是很常见的。 None
作为默认参数,并在函数体中对其进行评估:
b=0
def a():
global b
return b
def c(d=None):
if d is None:
d = a()
return d
答案 3 :(得分:1)
我会对上面的内容略有不同:
b = 0
def a():
# unless you are writing changes to b, you do not have to make it a global
return b
def c(d=None, get_d=a):
if d is None:
d = get_d()
return d