Python默认参数评估 [英] Python Default Arguments Evaluation
问题描述
我正在阅读python文档版本2.7.10中的python教程,遇到了这样的事情。
I was reading the python tutorial from Python Documentation Release 2.7.10 and I came across something like this.
代码
def fun1(a,L=[]):
L.append(a)
return L
print fun1(1)
print fun1(2)
print fun1(3)
def fun2(a,L = None):
if L is None:
L=[]
L.append(a)
return L
print fun2(1)
print fun2(2)
print fun2(3)
输出
[1]
[1, 2]
[1, 2, 3]
[1]
[2]
[3]
Process finished with exit code 0
如果第一个函数 fun1()
中的 L = []
仅调用一次, fun1()
的输出就可以了。但是,为什么每次在 fun2()
中都会调用 L = None
。
If the L=[]
in the first function fun1()
is getting called only once , the output of fun1()
is fine. But then why L=None
is getting called every time in fun2()
.
推荐答案
定义函数时,将评估默认参数的值,但但函数主体仅被编译。您可以通过属性检查函数定义的结果。有一个 __ defaults __
属性,包含默认值,而 __ code __
属性,包含主体(因此在定义函数时创建)
When you define a function the values of the default arguments get evaluated, but the body of the function only get compiled. You can examine the result of the function definition via attributes. Theres a __defaults__
attribute containing the defaults and __code__
attribute containing the body (so these are created when the function is defined).
第二个示例中发生的事情是 None
确实在定义时得到了评估(其评估结果为 None
duh!),但是有条件地将 []
分配给 L
仅被编译并每次都运行(条件通过)。
What's happening in the second example is that None
do get evaluated at definition (it evaluates to None
duh!), but the code that conditionally assigns []
to L
only gets compiled and is run each time (the condition passes).
这篇关于Python默认参数评估的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!