Comparing boolean and int using isinstance(使用 isinstance 比较 boolean 和 int)
问题描述
有人能给我解释一下为什么 isinstance() 在以下情况下返回 True 吗?在编写代码时,我期望 False.
Can someone give me an explanation why isinstance() returns True in the following case? I expected False, when writing the code.
print isinstance(True, (float, int))
True
我的猜测是它的 Python 的内部子类化,零和一 - 无论是浮点数还是整数 - 都在用作布尔值时进行评估,但不知道确切的原因.
My guess would be that its Python's internal subclassing, as zero and one - whether float or int - both evaluate when used as boolean, but don't know the exact reason.
解决这种情况的最pythonic方法是什么?我可以使用 type() 但在大多数情况下,这被认为不那么 Pythonic.
What would be the most pythonic way to solve such a situation? I could use type() but in most cases this is considered less pythonic.
推荐答案
由于历史原因,bool 是 int 的子类,所以 True 是 int 的一个实例.(最初,Python 没有 bool 类型,返回真值的东西返回 1 或 0.当他们添加 bool 时,True 和 False 必须尽可能地替换 1 和 0 以实现向后兼容性,因此是子类化.)
For historic reasons, bool is a subclass of int, so True is an instance of int. (Originally, Python had no bool type, and things that returned truth values returned 1 or 0. When they added bool, True and False had to be drop-in replacements for 1 and 0 as much as possible for backward compatibility, hence the subclassing.)
解决"这个问题的正确方法取决于您认为问题是什么.
The correct way to "solve" this depends on exactly what you consider the problem to be.
- 如果你想让
True不再是int,那太糟糕了.这不会发生. 如果您想检测布尔值并以不同于其他整数的方式处理它们,您可以这样做:
- If you want
Trueto stop being anint, well, too bad. That's not going to happen. If you want to detect booleans and handle them differently from other ints, you can do that:
if isinstance(whatever, bool):
# special handling
elif isinstance(whatever, (float, int)):
# other handling
如果你想检测特定类正好是float或int的对象,拒绝子类,你可以这样做:
If you want to detect objects whose specific class is exactly float or int, rejecting subclasses, you can do that:
if type(whatever) in (float, int):
# Do stuff.
这篇关于使用 isinstance 比较 boolean 和 int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 isinstance 比较 boolean 和 int
基础教程推荐
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
