代码之家  ›  专栏  ›  技术社区  ›  Patriots299

Python封闭函数

  •  1
  • Patriots299  · 技术社区  · 6 年前

    我正在学习封闭函数,代码如下:

    def parent(x="Hello"):
        text = x
    
        def son():
            print(text)
    
        return son
    
    print(parent())
    

    为什么会这样 print(parent()) <function parent.<locals>.son at 0x00000136A32E9EA0> ?

    我注意到,如果我执行以下操作,它将打印“Hello”:

    def parent(x="Hello"):
        text = x
    
        def son():
            print(text)
    
        return son
    
    akin = parent()
    akin()
    

    两者之间有什么区别?

    2 回复  |  直到 6 年前
        1
  •  2
  •   DYZ    6 年前

    功能 parent 返回另一个函数。必须调用该函数才能生效:

    print(parent()())
    

    print((parent())()
    
        2
  •  0
  •   DYZ    6 年前

    在这里你需要归还儿子()

    def parent(x="Hello"):
        text = x
    
        def son():
            print(text)
    
        return son # return son()
    
    print(parent())
    

    def parent(x="Hello"):
        text = x
    
        def son():
            print(text)
    
        return son
    
    akin = parent()
    akin() # print(akin) will get the same output of first program
    

    不同的是每个函数都有一个内存地址,你引用一个没有括号()的函数会返回函数的地址。因此,在第一个程序中,您可以返回函数的内存地址,这样就可以使用parent()访问内容,或者从函数返回实际值,而不是返回地址