Python 3的输入()返回的str与相同的str li不同对象

2024-04-26 00:36:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我在python3中遇到了一个我不理解的有趣行为。我了解到,对于str、int等内置的不可变类型,它们不仅值相同(都包含“x”)的两个变量相等,而且实际上是同一个对象,这允许使用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

为什么会这样?在


Tags: 对象函数字符串testid类型inputis
3条回答

I've understood that with the built-in immutable types like str, int, etc, that not only are two variables of the same value (both contain 'x') equal, they are literally the same object, which allows the use of the is operator.

这是您的误解:关于ints和longs,它只对少数值有效;对于任何类型的字符串,对于一个模块的字符串,这可能是正确的,但在其他情况下则不然。在

但是there is a builtin function ^{}它实习任何给定的字符串。在

这是因为一个实现细节-一般来说,您不能依赖is返回{}。试试这个脚本:

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

这个指纹

^{pr2}$

在Jython上,is即使在第一次打印时也返回False。在

这是正确的行为。在

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

但是:

^{pr2}$

相关问题 更多 >

    热门问题