為什么bool是int的子類?當(dāng)通過python-memcached在memcached中存儲(chǔ)bool時(shí),我注意到它以整數(shù)形式返回。檢查庫(kù)的代碼向我顯示有一個(gè)地方isinstance(val, int)被檢查以將值標(biāo)記為整數(shù)。所以我在python shell中測(cè)試了它并注意到以下內(nèi)容:>>> isinstance(True, int)True>>> issubclass(bool, int)True但為什么究竟是bool一個(gè)子類int呢?它有點(diǎn)意義,因?yàn)椴紶栔祷旧鲜且粋€(gè)int,它可以只取兩個(gè)值,但它需要比實(shí)際整數(shù)少得多的操作/空間(沒有算術(shù),只有一點(diǎn)存儲(chǔ)空間)....
3 回答

守候你守候我
TA貢獻(xiàn)1802條經(jīng)驗(yàn) 獲得超10個(gè)贊
參見PEP 285 - 添加bool類型。相關(guān)段落:
6)bool應(yīng)該繼承自int嗎?
=>是的。
在理想的世界中,bool可能更好地實(shí)現(xiàn)為一個(gè)知道如何執(zhí)行混合模式算術(shù)的單獨(dú)整數(shù)類型。但是,從int繼承bool可以極大地簡(jiǎn)化實(shí)現(xiàn)(部分原因是所有調(diào)用PyInt_Check()的C代碼都將繼續(xù)工作 - 這對(duì)于int的子類返回true。

慕娘9325324
TA貢獻(xiàn)1783條經(jīng)驗(yàn) 獲得超4個(gè)贊
也可以help
用來檢查Bool
控制臺(tái)中的值:
幫助(真)
help(True)Help on bool object:class bool(int) | bool(x) -> bool | | Returns True when the argument x is true, False otherwise. | The builtins True and False are the only two instances of the class bool. | The class bool is a subclass of the class int, and cannot be subclassed. | | Method resolution order: | bool | int | object |
幫助(假)
help(False)Help on bool object:class bool(int) | bool(x) -> bool | | Returns True when the argument x is true, False otherwise. | The builtins True and False are the only two instances of the class bool. | The class bool is a subclass of the class int, and cannot be subclassed. | | Method resolution order: | bool | int | object
添加回答
舉報(bào)
0/150
提交
取消