Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/362.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
类型(4)==类型(int)在Python中为False?_Python_Python 2.7_Types_Integer - Fatal编程技术网

类型(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中,type
int
本身也是一个类型为
type
的对象。所以
type(int)
就是
type
。另一方面,
type(4)
int

>>> type(4) == int
True
因此,如果您想检查
type(4)
是否为type
int
,您应该写为

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