关于Python中数据对象的可变性

先贴上Python官网中对数据模型描述的几段话。(在python官网的 语言参考>>数据模型 那部分)

 

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.

 

An object’s type determines the operations that the object supports (e.g., “does it have a length?”) and also defines the possible values for objects of that type. The type() function returns an object’s type (which is an object itself). Like its identity, an object’s type is also unchangeable. 

 

The value of some objects can change. Objects whose value can change are said to be mutable; objects whose value is unchangeable once they are created are called immutable. (The value of an immutable container object that contains a reference to a mutable object can change when the latter’s value is changed; however the container is still considered immutable, because the collection of objects it contains cannot be changed. So, immutability is not strictly the same as having an unchangeable value, it is more subtle.) An object’s mutability is determined by its type; for instance, numbers, strings and tuples are immutable, while dictionaries and lists are mutable.

 

Some objects contain references to other objects; these are called containers. Examples of containers are tuples, lists and dictionaries. The references are part of a container’s value. In most cases, when we talk about the value of a container, we imply the values, not the identities of the contained objects; however, when we talk about the mutability of a container, only the identities of the immediately contained objects are implied. So, if an immutable container (like a tuple) contains a reference to a mutable object, its value changes if that mutable object is changed.

 

每个对象有: identity, type, value; 其中 identity 和 type 总是 不可变 的。

对于对象的值来说,有的可变,有的不可变。

例如:numbers, strings and tuples 是 不可变 的; dictionaries and lists 是 可变 的。

有些对象包含其它对象的引用,这些对象叫做容器(containers), 例如 tuples, lists and dictionaries.

这些引用是一个容器的 value 的一部分。通常,我们说到一个容器的 value 的时候,我们暗指的是该容器所包含的对象的 value, 而不是对象的 identities。

然而当我们说到一个容器的可变性的时候,我们暗指的是该容器直接包含的对象的 identity.

因此,如果一个不可变容器(比如 tuple)包含一个到可变对象的引用的时候,如果那个可变对象改变的话它的值就改变了。

以上算是对英文原文的选择性翻译,下面举个栗子:

以为理解了,真要写出来让别人能看懂的时候反倒自己又迷糊了,待加,待加

posted @ 2016-03-17 10:36  张不正  阅读(424)  评论(0编辑  收藏  举报
返回顶部