在下面的代码中,print(first)
返回first_child
函数的地址,这对我来说很有意义,因为parent()
函数返回对first_child
的引用,而不是first_child
函数本身-也就是说,parent()
返回first_child
而不是first_child()
。
由于返回的是对first_child
函数的引用,而不是函数本身,因此我不明白为什么print(first())
实际上返回first_child函数的输出--显示"Hi,I am Emma“。为什么/如何以这种方式调用first_child()
函数?
def parent(num):
def first_child():
return "Hi, I am Emma"
def second_child():
return "Call me Liam"
if num == 1:
return first_child
else:
return second_child
first = parent(1)
second = parent(2)
print(first)
print(first())
发布于 2019-04-01 01:58:50
您需要首先了解:在Python中,函数是一等公民。它们可以--也确实--表现得像正常变量。
忘记所有关于C或Java函数。可以将python函数看作是另一个变量--除非您可以调用它--也就是说,对于f
变量,f()
是有意义的。
现在让我们回到你的问题上,parent
返回first_child
或second_child
--它们就像是变量。现在,当您获取这些变量中的一个并将()
放在它们之后时,就会调用该变量。这个调用最终计算出您在parent
中定义的字符串--因此您会得到"Hi I am Emma“
您必须理解“对函数的引用”与python中的“函数本身”一样好。
如果你想要更多血淋淋的细节,请查看:https://medium.com/python-pandemonium/function-as-objects-in-python-d5215e6d1b0d
https://stackoverflow.com/questions/55443743
复制相似问题