Python——对象、值和类型

3.1. Objects, values and types 对象、值和类型

Objects are Python’s abstraction for data. All data in a Python program is represented by objects or by relations between objects. (In a sense, and in conformance to Von Neumann’s model of a “stored program computer,” code is also represented by objects.)

对象是 Python 对数据的抽象。 Python 程序中的所有数据都是由对象或对象之间的关系表示的。 (在某种意义上,在与冯 · 诺依曼的"存储程序计算机"模型一致的情况下,代码也可用 object 表示。)

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.

每个对象都有一个标识、一个类型和一个。 一个对象的标识一旦被创建,就永远不会改变; 您可以将其视为对象在内存中的地址。 "is"操作符比较两个对象的同一性; id ()函数返回一个表示其同一性的整数。

CPython implementation detail: For CPython, id(x) is the memory address where x is stored.

Cpython 的实现细节: 对于 CPython 来说,id (x)是存储 x 的内存地址。

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. [1]

对象的类型决定对象支持的操作(例如,“它有长度吗?”) 并定义该类型对象的可能值。 type()函数的作用是: 返回一个对象的类型(本身就是一个对象)。 像它的标识一样,对象的类型也是不可改变的。 [1]

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.

一些对象的值可以更改。 其值可以更改的对象称为可变对象; 其值一旦创建就不能更改的对象称为不可变对象。 (包含可变对象引用的不可变容器对象的值可以在后者的值被更改时更改; 但是,容器仍然被认为是不可变的,因为它所包含的对象的集合不能被更改。 因此,不可变性不等同于值不可变,它更加微妙 对象的可变性由它的类型决定; 例如,数字、字符串和元组是不可变的,而字典和列表是可变的。

t = (1, 2, 3)
t[0] = 4

程序报错:

Traceback (most recent call last):
  File "/home/ezreal/Downloads/a.py", line 6, in <module>
    t[0] = 4
TypeError: 'tuple' object does not support item assignment
[Finished in 0.1s with exit code 1]
t = (1, 2, [3, 4])    # 元组是不可变对象
t[2].append(5)    # 不可变对象里包含了可变对象列表
print(t)    # 值是可变的

运行结果:

(1, 2, [3, 4, 5])
[Finished in 0.1s]

Objects are never explicitly destroyed; however, when they become unreachable they may be garbage-collected. An implementation is allowed to postpone garbage collection or omit it altogether — it is a matter of implementation quality how garbage collection is implemented, as long as no objects are collected that are still reachable.

对象永远不会被显式地销毁; 但是,当它们变得不可访问时,它们可能会被垃圾收集。 允许实现延迟垃圾收集或完全省略垃圾收集ー只要没有收集到仍然可以访问的对象,如何实现垃圾收集就是一个实现质量问题。

t = (1, 2, [3, 4])
a = t
b = t

del t    # del 删除的只是引用(变量),而不是对象本身
del a
print(b)

运行结果:

(1, 2, [3, 4])
[Finished in 0.1s]

CPython implementation detail: CPython currently uses a reference-counting scheme with (optional) delayed detection of cyclically linked garbage, which collects most objects as soon as they become unreachable, but is not guaranteed to collect garbage containing circular references. See the documentation of the gc module for information on controlling the collection of cyclic garbage. Other implementations act differently and CPython may change. Do not depend on immediate finalization of objects when they become unreachable (so you should always close files explicitly).

Cpython 的实现细节: 目前 CPython 使用了引用计数机制,并且(可选的)延迟检测循环链接的垃圾,它可以在大多数对象变得无法访问时立即收集它们,但是不能保证收集包含循环引用的垃圾。 有关控制循环垃圾收集的信息,请参阅 gc 模块的文档。 其他实现的操作不同,CPython 也可能会改变。 当对象变得无法访问时,不要依赖于对象的立即终结(因此您应该总是显式地关闭文件)。

Note that the use of the implementation’s tracing or debugging facilities may keep objects alive that would normally be collectable. Also note that catching an exception with a ‘try…except’ statement may keep objects alive.

请注意,使用实现的跟踪或调试工具可能会让通常可以收集的对象保持活动状态。 还要注意,使用’try… except’语句捕获异常可能会让对象保持活动状态。

Some objects contain references to “external” resources such as open files or windows. It is understood that these resources are freed when the object is garbage-collected, but since garbage collection is not guaranteed to happen, such objects also provide an explicit way to release the external resource, usually a close() method. Programs are strongly recommended to explicitly close such objects. The ‘try…finally’ statement and the ‘with’ statement provide convenient ways to do this.

有些对象包含对"外部"资源(如打开的文件或窗口)的引用。 当对象被垃圾回收时,这些资源被释放,但是由于垃圾回收不一定会发生,这些对象还提供了释放外部资源的显式方法,通常是 close ()方法。 强烈建议使用程序显式地关闭这样的对象。try... finally语句和with语句提供了方便的途径。

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.

有些对象包含对其他对象的引用; 这些对象被称为容器。 容器的例子有元组、列表和字典。 引用是容器值的一部分。 在大多数情况下,当我们讨论容器的值时,我们暗示的是值,而不是包含的对象的标识; 然而,当我们讨论容器的可变性时,只暗示了立即包含的对象的标识。 因此,如果不可变容器(比如 tuple)包含对可变对象的引用,那么当可变对象被更改时,它的值就会发生变化。

Types affect almost all aspects of object behavior. Even the importance of object identity is affected in some sense: for immutable types, operations that compute new values may actually return a reference to any existing object with the same type and value, while for mutable objects this is not allowed. E.g., after a = 1; b = 1, a and b may or may not refer to the same object with the value one, depending on the implementation, but after c = []; d = [], c and d are guaranteed to refer to two different, unique, newly created empty lists. (Note that c = d = [] assigns the same object to both c and d.)

类型几乎影响对象行为的所有方面。 甚至对象标识的重要性在某种意义上也会受到影响: 对于不可变类型,计算新值的操作实际上可能会返回对具有相同类型和值的任何现有对象的引用,而对于可变对象则不允许这样做。 例如,在 a 1; b1之后,a 和 b 可能会或者不会引用同一个值为1的对象,这取决于实现方式,但是在 c [] ; d []之后,c 和 d 肯定会引用两个不同的、唯一的、新创建的空列表。 (注意,c d []为 c 和 d 分配了相同的对象)

Reference

[1] https://docs.python.org/3/reference/datamodel.html?highlight=data model#objects-values-and-types

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值