鍍金池/ 教程/ Python/ 從函數中返回函數
<code>open</code>函數
Python 2系列版本
可迭代對象(Iterable)
異常
在函數中嵌入裝飾器
你的第一個裝飾器
上下文管理器(Context managers)
<code>set</code>(集合)數據結構
裝飾器類
字典推導式(<code>dict</code> comprehensions)
<code>Reduce</code>
捐贈名單
<code>Filter</code>
<code>try/else</code>從句
*args 的用法
<code>dir</code>
處理異常
<code>else</code>從句
對象自省
For - Else
18. 一行式
Python 3.2及以后版本
Global和Return
基于類的實現
容器(<code>Collections</code>)
23. 協(xié)程
推薦閱讀
譯者后記
<code>*args</code> 和 <code>**kwargs</code>
**kwargs 的用法
生成器(Generators)
迭代(Iteration)
基于生成器的實現
將函數作為參數傳給另一個函數
日志(Logging)
三元運算符
<code>inspect</code>模塊
枚舉
Map,Filter 和 Reduce
各種推導式(comprehensions)
從函數中返回函數
列表推導式(<code>list</code> comprehensions)
處理多個異常
帶參數的裝飾器
對象變動(Mutation)
22. 目標Python2+3
迭代器(Iterator)
虛擬環(huán)境(virtualenv)
<code>__slots__</code>魔法
什么時候使用它們?
Python/C API
<code>Map</code>
SWIG
授權(Authorization)
裝飾器
一切皆對象
使用C擴展
使用 <code>*args</code> 和 <code>**kwargs</code> 來調用函數
17. <code>lambda</code>表達式
集合推導式(<code>set</code> comprehensions)
<code>type</code>和<code>id</code>
在函數中定義函數
<code>finally</code>從句
CTypes
調試(Debugging)
使用場景
生成器(Generators)
多個return值
關于原作者
函數緩存 (Function caching)
Python進階

從函數中返回函數

其實并不需要在一個函數里去執(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語句中我們返回greetwelcome,而不是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