2012-07-23 19 views
4

可能重复:
Python “is” operator behaves unexpectedly with integers为什么不能用“is”来比较数字?

我通常使用type(x) == type(y)进行比较,如果类型相同。然后使用x==y来比较数值是否相等。

但是,有人提议可以只使用z1 is z2来比较z1z2是否包含具有完全相同值的相同类型的数字。在很多情况下,它会成功(特别是对于正面整数)。

但是,有时相同的数字(主要是负整数)可能有几个不同的实例。这是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] 
+3

http://stackoverflow.com/questions/306313/python-is-operator-behaves-unexpectedly-with-integers也有你的答案 – 2012-07-23 18:43:00

+6

谁提出的?他们应该被打了。 – delnan 2012-07-23 18:43:04

+1

对于一小部分整数,这是真实的(在CPython中)。不应该依赖这种行为,因为它不能保证在python实现中是相同的。 – 2012-07-23 18:56:16

回答

6

是。只有几个接近于0的数字(正如你发现的那样比正数多,否则是被编译器实现为)。由于表达式可能会导致此范围之外的数字,因此应使用is从不使用来检查相等性。

+0

你知道这些数字的范围吗? (我相信它是-5到256)。注意到interning行为不能保证,并且在所有的python实现中可能都不一样,这也很重要。 – 2012-07-23 18:53:44

+1

@JoelCornett它们真的没关系,因为正如你所提到的那样,它依赖于实现。 – 2012-07-23 18:54:33

+0

表达式的结果是无关紧要的。因为ints的实现依赖于实现,所以'should'应该用于检查是否相等(EVER)。 – 2012-07-23 18:55:46

0

is唯一正确的用法是比较对象的身份相同性。要比较价值等同性,请使用==

0

'is'关键字比较两个对象(基本上是存储它们的内存位置)的标识,而不是值。它不应该用来检查是否相等。

由于解释器的具体实现,'is'关键字在您的案例中成功了几次 - 编译器存储了一些数字以便于访问。你不应该期望或依赖这种行为。

1

按照Python documentation

运营商is和对象标识is not试验:x is y当且仅当xy是同一对象是真实的。 x is not y产生逆真值。

所以,即使x和y是相同类型并且相等,它们可能不会满足is关系。

相关问题