class bool([x])
該內(nèi)置函數(shù)本質(zhì)上是在調(diào)用 bool 類的構(gòu)造函數(shù),從而獲得一個布爾(bool)對象。bool 類僅有 False 和 True 兩個實例 (詳見 Boolean Values)。bool 類是 int 類的子類(詳見 Numeric Types — int, float, complex),但不能為 bool 類創(chuàng)建子類。
Tips:在數(shù)值上下文中(numeric contexts) :False 被視作 0,True 被視作 1。
>>> 1 + True
2
對于bool() ,如果省略 x 參數(shù),則會返回 False。
>>> bool()
False
如果存在 x 參數(shù),bool() 會使用標(biāo)準(zhǔn)真值測試對 x 進(jìn)行轉(zhuǎn)換。當(dāng) x 的真值為 false 時,bool() 會返回 False ;反之則返回 True。
>>> bool(1)
True
>>> bool(0)
False
>>> bool("False") # 非空字符串始終為True
True
>>> bool([0, 0])
True
>>> bool([])
False
>>> bool(2+2)
True
真值為 false 的對象
默認(rèn)情況下,對象的真值為 true,除非存在以下兩種情況:
- 對象中定義了
__bool__()方法,并且該方法返回False - 對象中定義了
__len__()方法,并且該方法返回0
如果同時定義了上述兩種方法, __bool__() 的優(yōu)先級高于 __len__() 。
>>> class Cls():
def __bool__(self):
return True
def __len__(self):
return 0
>>> a_cls = Cls()
>>> bool(a_cls)
True
下面是真值為 false 的內(nèi)置對象:
- 常量
None和False被定義為 false - 任何等于 0 的數(shù)值類型:
0,0.0,0j,Decimal(0),Fraction(0, 1) - 空序列(sequences)和集合(collections):
'',(),[],{},set(),range(0)