类型(4)==类型(int)在Python中为False?
我尝试了类型(4)==类型(int)在Python中为False?,python,python-2.7,types,integer,Python,Python 2.7,Types,Integer,我尝试了type(4)==type(int),它返回False,但是print type(4)返回,所以4显然是int >>> type(int) <type 'type'> >>> type(4) <type 'int'> 不明白为什么第一个语句返回False而不是True?看这个: >>> type(int) <type 'type'> >>> type(4) <type 'i
type(4)==type(int)
,它返回False
,但是print type(4)
返回
,所以4显然是int
>>> type(int)
<type 'type'>
>>> type(4)
<type 'int'>
不明白为什么第一个语句返回False
而不是True
?看这个:
>>> type(int)
<type 'type'>
>>> type(4)
<type 'int'>
int
的type
是类型本身:
甚至,因为int
是一个单例,所以像所有类型一样,应该是:
>>> type(4) is int
True
但是,测试类型的正确方法是使用:
isinstance()
还允许int
的任何子类通过此测试;子类始终被视为至少为int
。它包括您可以自己构建的任何自定义子类,并且仍然可以在代码中的任何其他地方作为int
工作。在Python中,typeint
本身也是一个类型为type
的对象。所以type(int)
就是type
。另一方面,type(4)
是int
>>> type(4) == int
True
因此,如果您想检查type(4)
是否为typeint
,您应该写为
type(4) == int
您正在将
int
与type(int)
进行比较,您应该:
type(4) == int
int的
类型是类型
4的类型是int
>>> type(int)
<type 'type'>
>>> type(4)
<type 'int'>
或者,您可以使用is
运算符进行类似操作
>>> type(4) is int
True
type(int)
是type
。@MartijnPieters,很好的捕捉和投票。但是如何检查数字的类型是否为int?我想区分int、float/double和非数值。@LinMa isinstance(num,int)我也学过同样的东西(宁愿isinstance
而不是type()=
);然而,读到这里,type(number)==int
感觉更像是python。如果你能谈谈为什么isinstance
是正确的方法,那就太好了。
>>> type(int)
<type 'type'>
>>> type(4)
<type 'int'>
>>> type(4) == int
True
>>> type(4) is int
True