简体   繁体   English

Python封闭函数

[英]Python enclosing functions

I am learning enclosing functions, and have the following code: 我正在学习封闭函数,并具有以下代码:

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

    def son():
        print(text)

    return son

print(parent())

Why does print(parent()) does not print "Hello", but rather prints <function parent.<locals>.son at 0x00000136A32E9EA0> ? 为什么print(parent())不打印“ Hello”,而是打印<function parent.<locals>.son at 0x00000136A32E9EA0>

I noticed that if I do the following, it will print "Hello": 我注意到,如果执行以下操作,它将打印“ Hello”:

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

    def son():
        print(text)

    return son

akin = parent()
akin()

What would be the difference between one and another? 彼此之间有什么区别?

Function parent returns another function. 函数parent返回另一个函数。 That function must be called to take effect: 必须调用该函数才能生效:

print(parent()())

Or, to emphasize the calling sequence: 或者,为了强调调用顺序:

print((parent())()

Here you need to return son() 在这里您需要返回son()

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

    def son():
        print(text)

    return son # return son()

print(parent())

Here you get difference result ,because are referring akin() 在这里,您会得到差异结果,因为引用的是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

Difference is every function a have memory address, you referring a function without parenthesises () will return address of the function . 区别在于每个函数都有一个内存地址,您在引用不带括号的函数时会返回该函数的地址。 So in your first program your returning the memory address of the function so you can access the content using parent()() or return the actual value from the function instead of returning address 因此,在第一个程序中,您将返回函数的内存地址,以便可以使用parent()()访问内容或从函数返回实际值,而不是返回地址

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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