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 技術手冊 第三版
類別與實體
|
135
讓我們以詳細到有點痛苦的方式來追蹤透過常規語法
x.name(arg)
進行的方
法呼叫中所涉及的概念步驟。在下列的情境中:
def f(a, b): ... # 帶有兩個引數的函式 f
class C(object):
name = f
x = C()
x
是類別
C
的一個實體物件,
name
這個識別字是
x
的一個方法(
C
的一個
屬性,其值為一個函式,在此就是函式
f
)之名稱,而
arg
是任何的運算
式。Python 首先會檢查
'name'
是否是
C
中作為屬性的一個覆寫式描述器
的名稱,不過它並不是,函式是描述器沒錯,因為它們的型別定義有方法
_ _get_ _
,但並非覆寫式的,因為它們的型別沒有定義方法
_ _set_ _
。接著
Python 會檢查
'name'
是否為
x._ _dict_ _
中的一個鍵值,但它不是。所以
Python 會在
C
中找尋
name
(如果
name
透過繼承關係在
C
_ _bases_ _
所含
的任一個基礎類別中被找到,所有的事情都還是會以同樣的方式運作)。
Python 注意到該屬性的值,即函式物件
f
,是一個描述器。因此,Python
呼叫
f._ _get_ _(x, C)
,這會創建一個已繫結方法物件,其
im_func
被設為
f
im_class
被設為
C
,而
im_self
被設為
x
。然後 Python
arg
作為唯一
引數來呼叫這個已繫結方法。已繫結方法會將
im_self
(即
x
)插入作為第
一個引數,而
arg
就變為第二個引數,以此呼叫已繫結方法的
im_func
(即
函式
f
)。這整體的效果就像是呼叫: ...
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