我在Python 3中遇到了一个我不太了解的有趣行为。我已经明白,使用内置的不可变类型如str,int等,不仅两个相同值的变量(都包含' x')相等,它们实际上是相同的object,允许使用is
运算符。但是,当我使用input()函数时,它似乎创建的字符串对象不是同一个对象,但具有相同的值。
这是我的python交互式提示:
$ python
Python 3.2 (r32:88452, Feb 20 2011, 11:12:31)
[GCC 4.2.1 (Apple Inc. build 5664)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> x = input()
test
>>> y = 'test'
>>> x is y
False
>>> x == y
True
>>> id(x)
4301225744
>>> id(y)
4301225576
为什么会这样?
答案 0 :(得分:2)
我已经明白,使用内置的不可变类型,如str,int等,不仅两个相同值的变量(都包含'x')相等,它们实际上是同一个对象,它允许使用is运算符。
这是你的错误观念:关于int
和long
s,这仅对少数几个值有效;对于任何类型的字符串,关于一个模块的字符串可能是真的,但不是其他。
但there is a builtin function intern()
实习任何给定的字符串。
答案 1 :(得分:1)
这是一种正确的行为。
x == y #True because they have a the same value
x is y #False because x isn't reference to y
id(x) == id(y) #False because as the above
可是:
x = input()
y = x #rewrite reference of x to another variable
y == x and x is y and id(x) == id(y) #True
答案 2 :(得分:1)
这是因为实施细节 - 您通常不能依赖is
返回True
。试试这个脚本:
x = 'test'
y = 'test'
print('%r: \'x == y\' is %s, \'x is y\' is %s' % (x, x == y, x is y))
x = 'testtest'
y = 'testtest'
print('%r: \'x == y\' is %s, \'x is y\' is %s' % (x, x == y, x is y))
for i in range(1, 100):
x = 'test' * i
y = 'test' * i
print('%d: %r: \'x == y\' is %s, \'x is y\' is %s' % (i, x, x == y, x is y))
if x is not y:
break
打印
'test': 'x == y' is True, 'x is y' is True
'testtest': 'x == y' is True, 'x is y' is True
1: 'test': 'x == y' is True, 'x is y' is True
2: 'testtest': 'x == y' is True, 'x is y' is False
在Jython上,即使在第一次打印中,is
也会返回False
。
答案 3 :(得分:0)
相同的值不保证是同一个实例。这只是一个你不能依赖的优化。使用is
的情况并不是很多次,请改用==
。
答案 4 :(得分:0)
我已经了解到内置的不可变类型如str,int等,不仅两个相同值的变量(都包含'x')相等,它们实际上是同一个对象
不,这不能得到保证,就像我说的橙色与你持有的橙色在物理上无法区分一样,我不能保证我没有其他橙色只是发生了看起来很相似。