Python Bool和int比较和带有布尔值的列表索引

Python Bool和int比较和带有布尔值的列表索引,第1张

Python Bool和int比较和带有布尔值的列表索引

发生的是布尔值实际上 整数。True为1,False为0。Bool是int的子类型

>>> isinstance(True, int)True>>> issubclass(bool, int)True

因此,它不是将它们转换为整数,而只是将它们用作整数。

(由于历史原因,布尔值是整数。在Python中存在布尔类型之前,人们使用整数0表示false和1表示true。因此,在添加布尔类型时,他们将布尔值设为整数以保持向后兼容性包含使用这些整数值的旧代码。例如,请参见http://www.peterbe.com/plog/bool-
is-int
。)

>>> 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.


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5666689.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存