鍍金池/ 教程/ Python/ 在函數(shù)中定義函數(shù)
<code>open</code>函數(shù)
Python 2系列版本
可迭代對象(Iterable)
異常
在函數(shù)中嵌入裝飾器
你的第一個裝飾器
上下文管理器(Context managers)
<code>set</code>(集合)數(shù)據(jù)結構
裝飾器類
字典推導式(<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
基于類的實現(xiàn)
容器(<code>Collections</code>)
23. 協(xié)程
推薦閱讀
譯者后記
<code>*args</code> 和 <code>**kwargs</code>
**kwargs 的用法
生成器(Generators)
迭代(Iteration)
基于生成器的實現(xiàn)
將函數(shù)作為參數(shù)傳給另一個函數(shù)
日志(Logging)
三元運算符
<code>inspect</code>模塊
枚舉
Map,F(xiàn)ilter 和 Reduce
各種推導式(comprehensions)
從函數(shù)中返回函數(shù)
列表推導式(<code>list</code> comprehensions)
處理多個異常
帶參數(shù)的裝飾器
對象變動(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> 來調(diào)用函數(shù)
17. <code>lambda</code>表達式
集合推導式(<code>set</code> comprehensions)
<code>type</code>和<code>id</code>
在函數(shù)中定義函數(shù)
<code>finally</code>從句
CTypes
調(diào)試(Debugging)
使用場景
生成器(Generators)
多個return值
關于原作者
函數(shù)緩存 (Function caching)
Python進階

在函數(shù)中定義函數(shù)

剛才那些就是函數(shù)的基本知識了。我們來讓你的知識更進一步。在Python中我們可以在一個函數(shù)中定義另一個函數(shù):

def hi(name="yasoob"):
    print("now you are inside the hi() function")

    def greet():
        return "now you are in the greet() function"

    def welcome():
        return "now you are in the welcome() function"

    print(greet())
    print(welcome())
    print("now you are back in the hi() function")

hi()
#output:now you are inside the hi() function
#       now you are in the greet() function
#       now you are in the welcome() function
#       now you are back in the hi() function

# 上面展示了無論何時你調(diào)用hi(), greet()和welcome()將會同時被調(diào)用。
# 然后greet()和welcome()函數(shù)在hi()函數(shù)之外是不能訪問的,比如:

greet()
#outputs: NameError: name 'greet' is not defined

那現(xiàn)在我們知道了可以在函數(shù)中定義另外的函數(shù)。也就是說:我們可以創(chuàng)建嵌套的函數(shù)。現(xiàn)在你需要再多學一點,就是函數(shù)也能返回函數(shù)。