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 技術手冊 第三版
特殊方法
|
153
_ _new_ _
中初始化不可變物件,其他的在
_ _init_ _
中進行
既然你可以在
__init__
__new__
中進行新實體大部分的初始化
動作,你可能會好奇何者才是最佳選擇。很簡單:除非你有特殊
的原因需要把初始化動作放在
__new__
中,不然就一律把它們放
__init__
。(如果一個型別是不可變的,其實體在
__init__
無法被變更以進行初始化,這種情形就是
__new__
確實得進行所
有初始化動作的特例。)這個建議會讓你的工作簡單一些,因為
__init__
是一個實體方法,而
__new__
是一個特化的類別方法。
__nonzero__ __nonzero_ _(self)
要把
x
當成真值或假值估算時(參閱前面的「Boolean 值」),例如
呼叫
bool(x)
的時候,v2 就會呼叫
x.__nonzero_ _()
,而這應該回
True
False
。如果
__nonzero_ _
沒有出現,Python 就會改為呼
__len_ _
,並在
x.__len_ _()
回傳
0
的時候把
x
視為假(因此,要
檢查一個容器是否不是空的,避免寫成
if len(container)>0:
,只要
寫成
if container:
就行了)。如果
__nonzero_ _
__len_ _
都沒出
現,Python 永遠都會將
x
視為真。
v3 中,這個特殊方法被改為較易讀的
__bool_ _
__repr__ __repr_ _(self)
呼叫
repr(x)
(在互動式直譯器中,當
x
是一個運算式述句的結果, ...
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