Home  >  Q&A  >  body text

python - 不理解函数作用域

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中文网2741 days ago362

reply all(1)I'll reply

  • PHP中文网

    PHP中文网2017-04-18 10:33:01

    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

    reply
    0
  • Cancelreply