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()
的输出是美好的.但是为什么 L=None
每次都在 fun2()
中被调用.
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
废话!),但是有条件地分配 []
到 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屋!