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