If we execute these assignment statements:

We know that a and b both refer to a string, but we don’t know whether they refer to the same string. To check whether two variables refer to the same object, you can use the is operator. And the result shows in this example, Python only created one string object, and both a and b refer to it.

In contrast, when you create two lists, you get two objects:

In this case we would say that the two lists are equivalent, because they have the same elements, but not identical, because they are not the same object. If two objects are identical, they are also equivalent, but if they are equivalent, they are not necessarily identical. Until now, we have been using ‘Object’ and ‘value’ interchangeably, but it is more precise to say that an object has a value. If you execute a = [1,2,3], a refers to a list object whose value is a particular sequence of elements. If another list has the same elements, we would say it has the same value.

Aliasing

If a refers to an object and you assign b = a, then both variables refer to the same object. For example if you execute:

The association of a variable with an object is called reference. In this example, there are two references to the same object. An object with more than one reference has, in some sense, more than one name, so we say that the object is aliased. If the aliased object is mutable, changes made with one alias affect the other:

Although this behaviour can be useful, it is sometimes unexpected or undesirable. In general, it is safer to avoid aliasing when you are working with mutable objects. For immutable objects like strings, aliasing is not as much of a problem. For example string, it almost never makes a difference whether a and b refer to the same string or not.

from Thinking in Python

最新文章

  1. 1Z0-053 争议题目解析
  2. 【Bootstrap Demo】入门例子创建
  3. Unix 用gdb分析core dump文件
  4. Field 'id' doesn't have a default value(jdbc连接错误)
  5. java文件上传和下载
  6. linux下查找某文件关键字
  7. 简析LIVE555中的延时队列
  8. [D3] 13. Cleaner D3 code with selection.call()
  9. 我和CPP的第二次约会
  10. cf C Bear and Prime Numbers
  11. Shell工具:jsondiff.sh
  12. 【第四篇】androidEventbus源代码阅读和分析
  13. JavaScript之BST
  14. 【linux之正则表达式】
  15. VM快照-克隆重要应用讲解及克隆后网卡问题解决
  16. HTML5 CSS3 诱人的实例 : 网页加载进度条的实现,下载进度条等
  17. javaEE REST 基于第三方框架Restlet
  18. 面试 10:玩转 Java 选择和插入排序,附冒泡最终源码
  19. DokuWiki 命名空间管理
  20. Django的rest_framework的分页组件源码分析

热门文章

  1. poj2965 The Pilots Brothers' refrigerator(直接计算或枚举Enum+dfs)
  2. pcap网络抓包 无法import pcap
  3. hive 运行sqlclient异常
  4. Maximum Bipartite Matching
  5. 一些.NET 项目中经常使用的类库
  6. POJ 3299 模拟
  7. 洛谷 P1983 车站分级 拓扑排序
  8. 洛谷 P1967 货车运输 LCA + 最小生成树
  9. C语言的常用printf打印占位符%d, %u, %f, %s, %c, %o, %x
  10. UNIX系统高级编程——第六章-系统数据文件和信息-总结