簡體   English   中英

Python封閉函數

[英]Python enclosing functions

我正在學習封閉函數,並具有以下代碼:

def parent(x="Hello"):
    text = x

    def son():
        print(text)

    return son

print(parent())

為什么print(parent())不打印“ Hello”,而是打印<function parent.<locals>.son at 0x00000136A32E9EA0>

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

def parent(x="Hello"):
    text = x

    def son():
        print(text)

    return son

akin = parent()
akin()

彼此之間有什么區別?

函數parent返回另一個函數。 必須調用該函數才能生效:

print(parent()())

或者,為了強調調用順序:

print((parent())()

在這里您需要返回son()

def parent(x="Hello"):
    text = x

    def son():
        print(text)

    return son # return son()

print(parent())

在這里,您會得到差異結果,因為引用的是akin()

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()()訪問內容或從函數返回實際值,而不是返回地址

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM