码迷,mamicode.com
首页 > 其他好文 > 详细

Objects and values

时间:2014-07-15 23:20:09      阅读:208      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   http   strong   os   

If we execute these assignment statements:

bubuko.com,布布扣                       

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:

bubuko.com,布布扣 

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:

 bubuko.com,布布扣

bubuko.com,布布扣

 

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:

 bubuko.com,布布扣

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

Objects and values,布布扣,bubuko.com

Objects and values

标签:des   style   blog   http   strong   os   

原文地址:http://www.cnblogs.com/ryansunyu/p/3841505.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!