使用 isinstance 比较布尔值和 int
- 2025-03-14 08:57:00
- admin 原创
- 8
问题描述:
有人能解释一下为什么isinstance()
在以下情况下返回 True 吗?编写代码时,我预期的是 False。
print isinstance(True, (float, int))
True
我的猜测是,它是 Python 的内部子类,因为零和一(无论是浮点数还是整数)在用作布尔值时都会被评估,但不知道具体原因。
解决这种情况最符合 Python 风格的方法是什么?我可以使用,type()
但在大多数情况下,这种方法被认为不太符合 Python 风格。
解决方案 1:
由于历史原因,bool
是的子类int
,因此True
是的实例int
。(最初,Python 没有 bool 类型,返回真值的东西返回 1 或 0。当他们添加时bool
,为了向后兼容,True 和 False 必须尽可能地成为 1 和 0 的直接替代品,因此进行了子类化。)
“解决”这个问题的正确方法取决于您认为问题到底是什么。
如果你想
True
停止做int
,那太糟糕了。这是不可能的。如果您想要检测布尔值并以不同于其他整数的方式处理它们,您可以这样做:
if isinstance(whatever, bool):
# special handling
elif isinstance(whatever, (float, int)):
# other handling
float
如果你想要检测特定类别恰好是或 的对象int
,并拒绝子类,你可以这样做:
if type(whatever) in (float, int):
# Do stuff.
如果您想检测所有浮点数和整数,那么您已经这样做了。
解决方案 2:
您可以查看方法解析顺序,并从那里找到所有超类:
>>> bool.__mro__
(<class 'bool'>, <class 'int'>, <class 'object'>)
解决方案 3:
是的,这是正确的,它是 int 的子类,您可以使用解释器来验证它:
>>> int.__subclasses__()
[<type 'bool'>]
解决方案 4:
如果您只想检查int
:
if type(some_var) is int:
return True
else:
return False
解决方案 5:
查看 Python 在 bool 和 int 上的一些行为(不是那么奇怪)
>>> 1 == True
True
>>> 0 == False
True
>>> True*5 == 0
False
>>> True*5 == 5
True
>>>
它们可以多么互换使用...!
从 boolobject.h (win py 2.7) 中,我可以看到 bool obj 的 int typedef。因此很明显,bool 继承了 int 的一些特征。
#ifndef Py_BOOLOBJECT_H
#define Py_BOOLOBJECT_H
#ifdef __cplusplus
extern "C" {
#endif
typedef PyIntObject PyBoolObject;
解决方案 6:
这是一个实例检查器,它使用 bool 来保证安全,并且接受单一类型或类型的元组,就像isinstance()
def isInst(o, of) -> bool:
if o is None: return False
cls = o.__class__
if isinstance(of, type):
return cls == of
else:
if cls == bool:
return bool in of
else:
for i in range(len(of)):
if cls == of[i]: return True
return False
相关推荐
热门文章
项目管理软件有哪些?
热门标签
云禅道AD