python - Python 可变对象中的引用与赋值

标签 python reference variable-assignment

作业:

>>> a = ['spam']
>>> b = ['spam']
>>> a is b
False

引用:

>>> c = ['spam']
>>> d = c
>>> c is d
True
  1. 以上两者有什么区别?
  2. 为什么赋值结果False
  3. 为什么引用结果 True

最佳答案

您的第一个代码段创建了两个 不同的唯一列表对象。因此 a is b 返回 false,因为 ab 指向不同的对象:

          +------+
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; the id() 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/

相关文章:

php - 取消设置 php 引用

php - 如何在 PHP 中通过引用传递变量来存储变量?

python - 在 numpy 数组中赋值

javascript - javascript中,内部作用域中的变量的重新声明会影响作用域外的变量

python - 我已经实现了一个简单的人工神经网络,但没有得到所需的输出

python - 如何制作字段名称与模型字段名称不同的 Django 模型表单?

python - OpenCv 链接器错误 : Symbol not found: ___itt_api_version_ptr__3_0

python - Numpy 数组仅将函数应用于某些元素

c++ - 为什么二维Array中的Range for要这样写?

C# int32 字面量只能存储在 long 数据类型中