关于函数调用

转载自:https://docs.pythontab.com/interpy/decorators/return_func_in_func/

 

 1 def hi(name="yasoob"):
 2     def greet():
 3         return "now you are in the greet() function"
 4 
 5     def welcome():
 6         return "now you are in the welcome() function"
 7 
 8     if name == "yasoob":
 9         return greet
10     else:
11         return welcome
12 
13 a = hi()
14 print(a)
15 #outputs: <function greet at 0x7f2143c01500>
16 
17 #上面清晰地展示了`a`现在指向到hi()函数中的greet()函数
18 #现在试试这个
19 
20 print(a())
21 #outputs: now you are in the greet() function

if/else语句中我们返回greetwelcome,而不是greet()welcome()。为什么那样?这是因为当你把一对小括号放在后面,这个函数就会执行;然而如果你不放括号在它后面,那它可以被到处传递,并且可以赋值给别的变量而不去执行它。

你明白了吗?让我再稍微多解释点细节。

当我们写下a = hi()hi()会被执行,而由于name参数默认是yasoob,所以函数greet被返回了,但由于返回的greet并没有被调用,所以在14行才只会打印出函数所在内存地址。如果我们把语句改为a = hi(name = "ali"),那么welcome函数将被返回。我们还可以打印出hi()(),这会输出now you are in the greet() function

 

posted on 2019-07-09 17:46  苦海舟  阅读(113)  评论(0)    收藏  举报

导航