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

Python 技術手冊 第三版

by lex Martelli, Anna Martelli Ravenscroft, Steve Holden
January 2018
Intermediate 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.

Read now

Unlock full access

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

測試驅動開發|使用 Python

測試驅動開發|使用 Python

Harry J.W. Percival

Publisher Resources

ISBN: 9789864766819