简体   繁体   English

为什么不使用非局部范围变量作为参数工作的默认值?

[英]Why doesn't using nonlocal scope variable as default value for parameter work?

Code would explain this much better :) 代码会更好地解释:)

def a():
    x=0
    def b(z=x):
        print("X: %d, Z: %d" % (x,z,))
    x=5
    b()

Result: 结果:

X: 5, Z: 0

What's going on here? 这里发生了什么?

(Ok, now I've figured it out) (好吧,现在我已经弄明白了)

Ok, the answer from the Python docs is: 好的,Python文档的答案是:

Default parameter values are evaluated when the function definition is executed. 执行函数定义时,将评估默认参数值。 This means that the expression is evaluated once, when the function is defined, and that the same “pre-computed” value is used for each call. 这意味着当定义函数时,表达式被计算一次,并且每次调用使用相同的“预先计算”值。

Fair enough. 很公平。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM