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 技術手冊 第三版
特殊方法
|
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.

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 进行数据分析(原书第2版)

利用 Python 进行数据分析(原书第2版)

Wes McKinney

Publisher Resources

ISBN: 9789864766819