[英]Python Immutability List in Tuple - Object or Value?
Can someone help me understand why the second comparison between z and c variables resolve as False?有人能帮我理解为什么 z 和 c 变量之间的第二次比较解析为 False 吗?
t = [1, 2, 3]
h = t
print(id(h), " ", id(t))
print(h is t)
x = ('bla', t)
y = ('bla', t)
z, c = str(x[1]), str(y[1])
print(id(z), " ", id(c))
print(z is c)
My initial impression is that x[1] and y[1] would be pointing to the same reference since we're directly assigning that index of the tuples to the t variable.我的初步印象是 x[1] 和 y[1] 将指向相同的引用,因为我们直接将元组的索引分配给 t 变量。 Does this mean Python is passing in the value of t rather than the object of the variable?
这是否意味着 Python 传递的是 t 的值而不是变量的 object? Why does h is t evaluate to True but z is c evaluate to false?
为什么 h 是 t 评估为真而 z 是 c 评估为假? *** scratches head ***
*** 挠头 ***
This has nothing to do with tuples themselves, but with str
being applied to basically anything that is not already a string:这与元组本身无关,但
str
基本上应用于任何还不是字符串的东西:
x = 0
x is x
# True
str(x) is str(x)
# => False
This is because str(x)
converts its argument into a new string each time.这是因为
str(x)
每次都将其参数转换为一个新字符串。
Immutability of a string is a necessary but not sufficient condition for having identical strings share the same object. There is some overhead in looking up a string to see if it already exists, so most of the time Python doesn't bother.字符串的不变性是相同字符串共享相同 object 的必要但不充分条件。查找字符串以查看它是否已经存在会产生一些开销,因此大多数情况下 Python 不会打扰。 It does provide a facility for interned strings so you can do it yourself if you want.
它确实为interned strings提供了一个工具,所以如果你愿意,你可以自己做。
>>> import sys
>>> str(0) is str(0)
False
>>> sys.intern(str(0)) is sys.intern(str(0))
True
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.