简体   繁体   中英

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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