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 技術手冊 第三版
158
|
4 章 物件導向的 Python
__len__ __len_ _(self)
呼叫
len(x)
會呼叫
x.__len_ _()
(其他內建函式需要知道容器
x
中有多少項目時也會)。
__len_ _
應該回傳一個
int
,也就是
x
項目的數量(number of items)。如果
__nonzero_ _
v3 中的
__
bool__
)沒有出現,Python 也會在 Boolean 情境下呼叫
x.__len_ _
()
來估算
x
,在這種情況下,如果容器是空的(即容器的長度為
0
),容器就會被視為假(false)。所有的容器都應該有
__len_ _
,除
非判斷它含有多少項目的成本太過昂貴。
__setitem__ __setitem_ _(self,key,value)
對於繫結
x
一個項目或切片的請求(通常是一個指定
x[key]=value
), Python 會呼叫
x.__setitem_ _(key,value)
。容器
x
應該只在它是可變的,所以其項目或切片可新增或重新繫結的時
候,才擁有
__setitem_ _
抽象基礎類別
抽象基礎類別(abstract base classesABCs)是物件導向(OO)設計中一
種重要的模式(pattern):它們是無法直接被繼承的類別,存在只是為了讓
具體類別(concrete classes,一般的類別,可被繼承的那種)擴充它們。
OO 設計的一個推薦做法是,永遠都不要擴充(extend)一個具體類別:如
果兩個具體類別彼此的共通之處多到你想讓其中一個繼承另一個,那麼就 ...
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