Python 可变对象中的引用与赋值 [英] Reference vs Assignment in Python mutable objects

查看:40
本文介绍了Python 可变对象中的引用与赋值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作业:

<预><代码>>>>a = ['垃圾邮件']>>>b = ['垃圾邮件']>>>a 是 b错误的

参考:

<预><代码>>>>c = ['垃圾邮件']>>>d = c>>>c 是 d真的

  1. 以上两者有什么区别?
  2. 为什么分配结果False?
  3. 为什么要参考结果 True?

解决方案

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

<前>+------+------> |列表 |+------++------+b ------> |列表 |+------+

您的第二个代码段创建了一个列表对象,并将 cd 都指向该对象,因此 c is d 返回 true:

<前>+------+c ------> |列表 |<------ d+------+

<小时>

注意以下内容,来自 http://docs.python.org/3/参考/datamodel.html:

<块引用>

每个对象都有一个身份、一个类型和一个值.一个对象的身份一旦被创建就永远不会改变;您可以将其视为对象在内存中的地址.is 运算符比较两个对象;id() 函数返回一个表示其身份的整数.

所以is==是非常不同的;前者比较对象身份,后者比较对象值.实际上,代码片段中的 == 测试将返回 true.

<小时>

鉴于上面的解释,可能会令人惊讶的是,故事与字符串略有不同:

<预><代码>>>>a = 'str'>>>b = 'str'>>>>>>a 是 b真的

这是由于 字符串实习,它发生在 CPython 中(即它是特定于实现的).因此,如果相同的字符串字面量出现在两个不同的地方,则相同的字符串对象将用于两者(有限制).

这在 Python 字符串实习"中有更详细的解释.

Assignment:

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

Reference:

>>> c = ['spam']
>>> d = c
>>> c is d
True

  1. What is the difference between above both?
  2. Why assignment results False?
  3. Why reference results True?

解决方案

Your first snippet creates two unique list objects, which are not the same. Hence a is b returns false because a and b are pointing to distinct objects:

          +------+
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

This is due to string interning, which occurs in CPython (i.e. it's implementation specific). Therefore, if the same string literal shows up in two different places, the same string object will be used for both (with restrictions).

This is explained in greater detail in "Python string interning".

这篇关于Python 可变对象中的引用与赋值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆