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 技術手冊 第三版
106
|
3 章 Python 語言
引數傳遞的語意
以傳統的術語來說,Python 中所有的引數傳遞(argument passing)都是
by value
的(雖然,在現代的術語中,說引數傳遞是
傳物件參考
by object reference
,會比較精確;本書的某些作者,但並非全部,也喜歡
call by sharing
這個同義詞)。舉例來說,如果你傳遞一個變數作為引數,
那麼 Python 傳入給函式物件的,會是該變數目前所指涉的物件(值),而
非變數本身,而那個值在函式的呼叫命名空間(call namespace)中會被繫
結至參數名稱。因此,一個函式無法重新繫結呼叫者的變數。然而,如果
你傳入一個可變物件(mutable object)作為引數,函式就可以請求變更那
個物件,因為 Python 傳遞的是物件本身,而非一個拷貝(copy)。重新繫
結(rebinding)一個變數和變動(mutating)一個物件,是完全不相交的
概念。舉例來說:
def f(x, y):
x = 23
y.append(42)
a = 77
b = [99]
f(a, b)
print(a, b) # 印出:77 [99, 42]
print
顯示
a
仍然繫結至
77
。函式
f
將其參數
x
重新繫結至
23
的動作對
f
的呼叫者沒有影響,特別是,並不影響剛好被用來傳入
77
作為參數值的呼
叫者變數的繫結。然而,
print
也顯示了
b
現在繫結的是
[99, 42]
b
現在
仍然跟呼叫之前一樣,繫結到相同的串列物件,但那個物件被變
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