Skip to Content
Python 技術手冊 第三版
book

Python 技術手冊 第三版

by lex Martelli, Anna Martelli Ravenscroft, Steve Holden
January 2018
Intermediate to advanced content levelIntermediate to advanced
856 pages
17h 17m
Chinese
GoTop Information, Inc.
Content preview from Python 技術手冊 第三版
函式
|
111
Python
的外層函式是一個「工廠(factory)」,專門生產以某些參數,例如前面例
子中引數
augend
的值,區分的一系列函式中的成員,而且經常可以幫助你
避免程式碼的重複。
僅限於 v3
nonlocal
關鍵字的行為類似於
global
,但它所指涉的是語彙
上的外圍函式(lexically surrounding function)的命名空間中的名稱。當
它出現在一個內嵌了數層深的巢狀函式定義中,編譯器會先搜尋包含那個
巢狀函式的最內層外圍函式,然後再往包含那個最內層外圍函式的函式的
命名空間去找,依此類推,直到找到該名稱,或已經沒有更外層的函式為
止,在這種情況下,編譯器會提出一個錯誤。
在前面章節中我們以一個函式屬性,然後再以一個全域變數分別實作過
counter」功能性,這裡有它僅限於 v3 的巢狀函式做法:
def make_counter():
count = 0
def counter():
nonlocal count
count += 1
return count
return counter
c1 = make_counter()
c2 = make_counter()
print(c1(), c1(), c1()) # 印出:1 2 3
print(c2(), c2()) # 印出:1 2
print(c1(), c2(), c1()) # 印出:4 3 5
這個做法與之前的做法比起來,主要的好處是,巢狀函式,就跟 OOP 的做
法一樣,能讓你製作獨立的計數器(
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

測試驅動開發|使用 Python

測試驅動開發|使用 Python

Harry J.W. Percival
Linux 内核观测技术BPF

Linux 内核观测技术BPF

David Calavera, Lorenzo Fontana

Publisher Resources

ISBN: 9789864766819