python - 不理解函数作用域
PHP中文网
PHP中文网 2017-04-18 10:31:01
0
1
406
def f(p, k):
    def g():
        print(k)
    if k == 0:
        f(g, 1)
    else:
        p()
f(None, 0)

我觉得在f(None, 0)执行后,执行到f(g, 1)k应该是1,但为什么执行还是0.

PHP中文网
PHP中文网

认证高级PHP讲师

reply all(1)
洪涛

This should be a closure, we can change this function

def f(k):
    def g():
        print(k)
    return g

a = 1
x = f(a)
a = 2
x()
# 打印出
# 1

Would this make it easier to understand?
You can read this blog, which explains the principle of closure at the bottom level. Detailed explanation of Python closures

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template