可能重复:
Python“is”运算符对整数的行为异常
通常我使用type(x) == type(y)
来比较类型是否相同。然后用于x==y
比较数值是否相等。
但是,有人提出,如果和包含具有完全相同值的相同类型的数字,则可以仅用于z1 is z2
比较。在许多情况下,它会成功(尤其是对于正整数)。z1
z2
但是,有时相同的数字(主要是负整数)可以有几个不同的实例。这是python的预期行为吗?
例如:
>>> for x in range(-20,125):
z1=x
z2=int(float(x))
if z1 is not z2:
print "z1({z1}; type = {typez1}; id={idz1}) is not z2({z2}; type = {typez2}; id={idz2})".format(z1=z1,typez1=type(z1),idz1=id(z1),z2=z2,typez2=type(z2),idz2=id(z2))
z1(-20; type = <type 'int'>; id=33869592) is not z2(-20; type = <type 'int'>; id=33870384)
z1(-19; type = <type 'int'>; id=33870480) is not z2(-19; type = <type 'int'>; id=33870408)
z1(-18; type = <type 'int'>; id=32981032) is not z2(-18; type = <type 'int'>; id=33870384)
z1(-17; type = <type 'int'>; id=33871368) is not z2(-17; type = <type 'int'>; id=33870408)
z1(-16; type = <type 'int'>; id=33869712) is not z2(-16; type = <type 'int'>; id=33870384)
z1(-15; type = <type 'int'>; id=33869736) is not z2(-15; type = <type 'int'>; id=33870408)
z1(-14; type = <type 'int'>; id=33869856) is not z2(-14; type = <type 'int'>; id=33870384)
z1(-13; type = <type 'int'>; id=33869280) is not z2(-13; type = <type 'int'>; id=33870408)
z1(-12; type = <type 'int'>; id=33868464) is not z2(-12; type = <type 'int'>; id=33870384)
z1(-11; type = <type 'int'>; id=33868488) is not z2(-11; type = <type 'int'>; id=33870408)
z1(-10; type = <type 'int'>; id=33869616) is not z2(-10; type = <type 'int'>; id=33870384)
z1(-9; type = <type 'int'>; id=33871344) is not z2(-9; type = <type 'int'>; id=33870408)
z1(-8; type = <type 'int'>; id=33869064) is not z2(-8; type = <type 'int'>; id=33870384)
z1(-7; type = <type 'int'>; id=33870336) is not z2(-7; type = <type 'int'>; id=33870408)
z1(-6; type = <type 'int'>; id=33870360) is not z2(-6; type = <type 'int'>; id=33870384)
>>> x
124
>>> print x
124
>>> import sys
>>> print sys.version
2.7.2+ (default, Oct 4 2011, 20:06:09)
[GCC 4.6.1]