作业:
>>> a = ['spam']
>>> b = ['spam']
>>> a is b
False
引用:
>>> c = ['spam']
>>> d = c
>>> c is d
True
- 以上两者有什么区别?
- 为什么赋值结果
False
? - 为什么引用结果
True
?
最佳答案
您的第一个代码段创建了两个 不同的唯一列表对象。因此 a is b
返回 false,因为 a
和 b
指向不同的对象:
+------+ a ------> | list | +------+ +------+ b ------> | list | +------+
Your second snippet creates a single list object, and points both c
and d
to that objects, hence c is d
return true:
+------+ c ------> | list | <------ d +------+
Note the following, from http://docs.python.org/3/reference/datamodel.html:
Every object has an identity, a type and a value. An object’s identity never changes once it has been created; you may think of it as the object’s address in memory. The
is
operator compares the identity of two objects; theid()
function returns an integer representing its identity.
So is
and ==
are very different; while the former compares object identity, the latter compares object values. Indeed, ==
tests in your snippets would return true.
Given the explanation above, it may come as a surprise that that the story is slightly different with strings:
>>> a = 'str'
>>> b = 'str'
>>>
>>> a is b
True
这是由于 string interning ,它出现在 CPython 中(即它是特定于实现的)。因此,如果相同的字符串文字出现在两个不同的地方,则相同的字符串对象将用于两者(有限制)。
这在 "Python string interning" 中有更详细的解释。 .
关于python - Python 可变对象中的引用与赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21092937/