我试过了 type(4) == type(int)
,返回 False
,但是print type(4)
返回 <type 'int'>
, 所以 4 显然是 int
.
困惑为什么第一个语句返回 False
而不是 True
?
最佳答案
int
的类型
是类型本身:
>>> type(int)
<type 'type'>
您可以直接与int
比较; int
毕竟是一种类型,正如我们在上面建立的那样:
>>> type(4) == int
True
甚至,因为 int
是单例,所以所有类型都应该是:
>>> type(4) is int
True
但是,测试类型的正确方法是使用 isinstance()
function :
>>> isinstance(4, int)
True
isinstance()
还允许 int
的任何子类通过此测试;一个子类总是被认为是至少一个int
。这包括您可以自己构建的任何自定义子类,并且仍然可以在代码的其他任何地方作为 int
工作。
关于python - type(4) == type(int) 在 Python 中是 False 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38006826/