其實并不需要在一個函數里去執(zhí)行另一個函數,我們也可以將其作為輸出返回出來:
def hi(name="yasoob"):
def greet():
return "now you are in the greet() function"
def welcome():
return "now you are in the welcome() function"
if name == "yasoob":
return greet
else:
return welcome
a = hi()
print(a)
#outputs: <function greet at 0x7f2143c01500>
#上面清晰地展示了`a`現在指向到hi()函數中的greet()函數
#現在試試這個
print(a())
#outputs: now you are in the greet() function
再次看看這個代碼。在if/else
語句中我們返回greet
和welcome
,而不是greet()
和welcome()
。為什么那樣?這是因為當你把一對小括號放在后面,這個函數就會執(zhí)行;然而如果你不放括號在它后面,那它可以被到處傳遞,并且可以賦值給別的變量而不去執(zhí)行它。
你明白了嗎?讓我再稍微多解釋點細節(jié)。
當我們寫下a = hi()
,hi()
會被執(zhí)行,而由于name
參數默認是yasoob,所以函數greet
被返回了。如果我們把語句改為a = hi(name = "ali")
,那么welcome
函數將被返回。我們還可以打印出hi()()
,這會輸出now you are in the greet() function。