3. Data model数据模型

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

Objects are Python’s abstraction for data. 是Python对数据的抽象。All data in a Python program is represented by objects or by relations between objects. Python程序中的所有数据都由对象或对象之间的关系表示。(In a sense, and in conformance to Von Neumann’s model of a “stored program computer”, code is also represented by objects.)(在某种意义上,与冯·诺依曼的“存储程序计算机”模型一致,代码也由对象表示。)

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:CPython实施详情: For CPython, id(x) is the memory address where x is stored.对于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). type()函数的作用是:返回对象的类型(即对象本身)。Like its identity, an object’s type is also unchangeable. 与其标识一样,对象的类型也是不可更改的。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.对象的易变性由其类型决定;例如,数字、字符串和元组是不可变的,而字典和列表是可变的。

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.允许一个实现推迟垃圾收集或完全忽略垃圾收集—只要没有收集到仍然可以访问的对象,垃圾收集的实现方式就事关实现质量。

CPython implementation detail:CPython实施详情: 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. CPython目前使用一种引用计数方案,该方案对循环链接垃圾进行延迟检测(可选),它会在无法访问大多数对象时立即收集这些对象,但不能保证收集包含循环引用的垃圾。See the documentation of the gc module for information on controlling the collection of cyclic garbage. Other implementations act differently and CPython may change. 有关控制循环垃圾收集的信息,请参阅gc模块的文档。其他实现的行为不同,CPython可能会改变。Do not depend on immediate finalization of objects when they become unreachable (so you should always close files explicitly).当对象变得不可访问时,不要依赖于对象的立即终结(因此您应该始终显式关闭文件)。

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 ‘tryexcept’ statement may keep objects alive.还请注意,使用“tryexcept”语句捕获异常可能会使对象保持活动状态。

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. 可以理解,当对象被垃圾收集时,这些资源会被释放,但由于垃圾收集不一定会发生,因此这些对象还提供了释放外部资源的显式方法,通常是close()方法。Programs are strongly recommended to explicitly close such objects. 强烈建议使用程序显式关闭此类对象。The ‘tryfinally’ statement and the ‘with’ statement provide convenient ways to do this.tryfinally”语句和“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.因此,如果不可变容器(如元组)包含对可变对象的引用,那么如果可变对象发生更改,其值也会更改。

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. 例如,a = 1; b = 1后,ab可能引用或不引用值为1的同一对象,具体取决于实现,但在c = []; d = []之后,cd保证引用两个不同的、唯一的、新创建的空列表。(Note that c = d = [] assigns the same object to both c and d.)(请注意,c=d=[]将相同的对象分配给cd。)

3.2. The standard type hierarchy标准类型层次结构

Below is a list of the types that are built into Python. 下面是Python中内置的类型列表。Extension modules (written in C, Java, or other languages, depending on the implementation) can define additional types. 扩展模块(使用C、Java或其他语言编写,具体取决于实现)可以定义其他类型。Future versions of Python may add types to the type hierarchy (e.g., rational numbers, efficiently stored arrays of integers, etc.), although such additions will often be provided via the standard library instead.Python的未来版本可能会将类型添加到类型层次结构中(例如,有理数、高效存储的整数数组等),尽管这种添加通常会通过标准库提供。

Some of the type descriptions below contain a paragraph listing ‘special attributes.’ 下面的一些类型描述包含一段“特殊属性”。These are attributes that provide access to the implementation and are not intended for general use. 这些属性提供了对实现的访问,并不打算用于一般用途。Their definition may change in the future.他们的定义将来可能会改变。

None

This type has a single value. 此类型只有一个值。There is a single object with this value. 有一个对象具有此值。This object is accessed through the built-in name None. 此对象通过内置名称None访问。It is used to signify the absence of a value in many situations, e.g., it is returned from functions that don’t explicitly return anything. 它用于表示在许多情况下没有值,例如,它是从没有显式返回任何内容的函数返回的。Its truth value is false.其真值为假。

NotImplemented

This type has a single value. 此类型只有一个值。There is a single object with this value. 有一个对象具有此值。This object is accessed through the built-in name NotImplemented. 此对象通过内置名称NotImplemented访问。Numeric methods and rich comparison methods should return this value if they do not implement the operation for the operands provided. 如果数字方法和富比较方法未对提供的操作数执行运算,则应返回此值。(The interpreter will then try the reflected operation, or some other fallback, depending on the operator.) (然后,解释器将根据运算符的不同,尝试反射操作或其他回退操作。)It should not be evaluated in a boolean context.不应在布尔上下文中对其求值。

See Implementing the arithmetic operations for more details.有关更多详细信息,请参阅实现算术运算

Changed in version 3.9: 在版本3.9中更改:Evaluating NotImplemented in a boolean context is deprecated. 在布尔上下文中计算NotImplemented是建议弃用的。While it currently evaluates as true, it will emit a DeprecationWarning. 虽然它当前的计算结果为true,但它将发出一个DeprecationWarningIt will raise a TypeError in a future version of Python.它将在Python的未来版本中引发TypeError

Ellipsis

This type has a single value. 此类型只有一个值。There is a single object with this value. 有一个对象具有此值。This object is accessed through the literal ... or the built-in name Ellipsis. 此对象通过文本...或内置的名称Ellipsis来访问。Its truth value is true.它的真值是true

numbers.Number

These are created by numeric literals and returned as results by arithmetic operators and arithmetic built-in functions. 它们由数字文本创建,并由算术运算符和算术内置函数作为结果返回。Numeric objects are immutable; once created their value never changes. 数字对象是不可变的;一旦创造了价值,就永远不会改变。Python numbers are of course strongly related to mathematical numbers, but subject to the limitations of numerical representation in computers.Python数字当然与数学数字密切相关,但受计算机中数字表示的限制。

The string representations of the numeric classes, computed by __repr__() and __str__(), have the following properties:__repr__()__str__()计算的数字类的字符串表示具有以下属性:

  • They are valid numeric literals which, when passed to their class constructor, produce an object having the value of the original numeric.它们是有效的数字文本,当传递给类构造函数时,会生成一个具有原始数字值的对象。

  • The representation is in base 10, when possible.如果可能,表示形式以10为底。

  • Leading zeros, possibly excepting a single zero before a decimal point, are not shown.不显示前导零,可能小数点前的单个零除外。

  • Trailing zeros, possibly excepting a single zero after a decimal point, are not shown.不显示尾随零,可能小数点后的单个零除外。

  • A sign is shown only when the number is negative.只有当数字为负数时才会显示符号。

Python distinguishes between integers, floating point numbers, and complex numbers:Python区分整数、浮点数和复数:

numbers.Integral

These represent elements from the mathematical set of integers (positive and negative).这些表示整数(正整数和负整数)数学集合中的元素。

There are two types of integers:有两种类型的整数:

Integers 整型数(int)

These represent numbers in an unlimited range, subject to available (virtual) memory only. 表示无限范围内的数字,仅受可用(虚拟)内存的限制。For the purpose of shift and mask operations, a binary representation is assumed, and negative numbers are represented in a variant of 2’s complement which gives the illusion of an infinite string of sign bits extending to the left.为了移位和掩码操作的目的,假设使用二进制表示,负数用2的补码的变体表示,这给人一种符号位无限串向左扩展的错觉。

Booleans布尔值 (bool)

These represent the truth values False and True. 这些表示真值FalseTrueThe two objects representing the values False and True are the only Boolean objects. 表示值FalseTrue的两个对象是唯一的布尔对象。The Boolean type is a subtype of the integer type, and Boolean values behave like the values 0 and 1, respectively, in almost all contexts, the exception being that when converted to a string, the strings "False" or "True" are returned, respectively.布尔类型是整数类型的子类型,在几乎所有上下文中,布尔值的行为分别类似于值0和1,但当转换为字符串时,将分别返回字符串"False""True"

The rules for integer representation are intended to give the most meaningful interpretation of shift and mask operations involving negative integers.整数表示规则旨在对涉及负整数的移位和掩码操作给出最有意义的解释。

numbers.Real (float)

These represent machine-level double precision floating point numbers. 它们表示机器级双精度浮点数。You are at the mercy of the underlying machine architecture (and C or Java implementation) for the accepted range and handling of overflow. 对于溢出的可接受范围和处理,您将任由底层机器体系结构(以及C或Java实现)的摆布。Python does not support single-precision floating point numbers; the savings in processor and memory usage that are usually the reason for using these are dwarfed by the overhead of using objects in Python, so there is no reason to complicate the language with two kinds of floating point numbers.Python不支持单精度浮点数;处理器和内存使用方面的节省(通常是使用它们的原因)与在Python中使用对象的开销相比相形见绌,因此没有理由使用两种浮点数使语言复杂化。

numbers.Complex (complex)

These represent complex numbers as a pair of machine-level double precision floating point numbers. 它们将复数表示为一对机器级双精度浮点数。The same caveats apply as for floating point numbers. 同样的注意事项也适用于浮点数。The real and imaginary parts of a complex number z can be retrieved through the read-only attributes z.real and z.imag.可以通过只读属性z.realz.imag检索复数z的实部和虚部。

Sequences序列号

These represent finite ordered sets indexed by non-negative numbers. 这些表示由非负数索引的有限有序集。The built-in function len() returns the number of items of a sequence. 内置函数len()返回序列的项数。When the length of a sequence is n, the index set contains the numbers 0, 1, …, n-1. 当序列的长度为n时,索引集包含数字0、1、n-1。Item i of sequence a is selected by a[i].序列a的项目ia[i]选择。

Sequences also support slicing: a[i:j] selects all items with index k such that i <= k < j. 序列还支持切片:a[i:j]选择索引为k的所有项目,以便i<=k<jWhen used as an expression, a slice is a sequence of the same type. 当用作表达式时,切片是相同类型的序列。This implies that the index set is renumbered so that it starts at 0.这意味着索引集将重新编号,以便从0开始。

Some sequences also support “extended slicing” with a third “step” parameter: a[i:j:k] selects all items of a with index x where x = i + n*k, n >= 0 and i <= x < j.一些序列还支持使用第三个“步长”参数进行“扩展切片”:a[i:j:k]选择索引为xa的所有项目,其中x = i + n*kn>=0i<=x<j

Sequences are distinguished according to their mutability:序列根据其可变性进行区分:

Immutable sequences不可变序列

An object of an immutable sequence type cannot change once it is created. 不可变序列类型的对象一旦创建就不能更改。(If the object contains references to other objects, these other objects may be mutable and may be changed; however, the collection of objects directly referenced by an immutable object cannot change.)(如果对象包含对其他对象的引用,则这些其他对象可能是可变的,并且可能会更改;但是,不可变对象直接引用的对象集合不能更改。)

The following types are immutable sequences:以下类型是不可变序列:

Strings

A string is a sequence of values that represent Unicode code points. 字符串是表示Unicode代码点的值序列。All the code points in the range U+0000 - U+10FFFF can be represented in a string. U+0000 - U+10FFFF范围内的所有代码点都可以用字符串表示。Python doesn’t have a char type; instead, every code point in the string is represented as a string object with length 1. Python没有char类型;相反,字符串中的每个代码点都表示为长度为1的字符串对象。The built-in function ord() converts a code point from its string form to an integer in the range 0 - 10FFFF; chr() converts an integer in the range 0 - 10FFFF to the corresponding length 1 string object. 内置函数ord()将代码点从字符串形式转换为0 - 10FFFF范围内的整数;chr()0 - 10FFFF范围内的整数转换为相应的长度为1的字符串对象。str.encode() can be used to convert a str to bytes using the given text encoding, and bytes.decode() can be used to achieve the opposite.str.encode()可用于使用给定的文本编码将str转换为bytes,而bytes.decode()可用于实现相反的效果。

Tuples

The items of a tuple are arbitrary Python objects. 元组的项是任意Python对象。Tuples of two or more items are formed by comma-separated lists of expressions. 两个或多个项的元组由逗号分隔的表达式列表组成。A tuple of one item (a ‘singleton’) can be formed by affixing a comma to an expression (an expression by itself does not create a tuple, since parentheses must be usable for grouping of expressions). 一个项的元组(“单元组”)可以通过在表达式上附加逗号来形成(表达式本身不会创建元组,因为括号必须可用于表达式分组)。An empty tuple can be formed by an empty pair of parentheses.空元组可以由一对空括号组成。

Bytes

A bytes object is an immutable array. 字节对象是一个不可变数组。The items are 8-bit bytes, represented by integers in the range 0 <= x < 256. 这些项是8位字节,由0<=x<256范围内的整数表示。Bytes literals (like b'abc') and the built-in bytes() constructor can be used to create bytes objects. 字节文本(如b'abc')和内置的bytes()构造函数可用于创建字节对象。Also, bytes objects can be decoded to strings via the decode() method.此外,字节对象可以通过decode()方法解码为字符串。

Mutable sequences可变序列

Mutable sequences can be changed after they are created. 可变序列可以在创建后更改。The subscription and slicing notations can be used as the target of assignment and del (delete) statements.订阅和切片符号可以用作赋值和del(delete)语句的目标。

There are currently two intrinsic mutable sequence types:目前有两种内在可变序列类型:

Lists列表

The items of a list are arbitrary Python objects. 列表中的项目是任意Python对象。Lists are formed by placing a comma-separated list of expressions in square brackets. 列表是通过将逗号分隔的表达式列表放在方括号中形成的。(Note that there are no special cases needed to form lists of length 0 or 1.)(请注意,形成长度为0或1的列表不需要特殊情况。)

Byte Arrays字节数组

A bytearray object is a mutable array. bytearray对象是可变数组。They are created by the built-in bytearray() constructor. 它们由内置的bytearray()构造函数创建。Aside from being mutable (and hence unhashable), byte arrays otherwise provide the same interface and functionality as immutable bytes objects.字节数组除了是可变的(因此是不可破坏的),还提供与不可变bytes对象相同的接口和功能。

The extension module array provides an additional example of a mutable sequence type, as does the collections module.扩展模块arraycollections模块提供了可变序列类型的另一个示例。

Set types集类型

These represent unordered, finite sets of unique, immutable objects. 这些表示无序的、有限的、唯一的、不可变的对象集。As such, they cannot be indexed by any subscript. 因此,它们不能被任何下标索引。However, they can be iterated over, and the built-in function len() returns the number of items in a set. 但是,可以对它们进行迭代,内置函数len()返回集合中的项数。Common uses for sets are fast membership testing, removing duplicates from a sequence, and computing mathematical operations such as intersection, union, difference, and symmetric difference.集合的常见用途是快速成员身份测试、从序列中删除重复项以及计算数学运算,如交集、并集、差分和对称差分。

For set elements, the same immutability rules apply as for dictionary keys. 对于集合元素,适用与字典键相同的不变性规则。Note that numeric types obey the normal rules for numeric comparison: if two numbers compare equal (e.g., 1 and 1.0), only one of them can be contained in a set.请注意,数字类型遵守数字比较的常规规则:如果两个数字比较相等(例如11.0),则一个集中只能包含其中一个。

There are currently two intrinsic set types:当前有两种内在集类型:

Sets

These represent a mutable set. 这些表示可变集。They are created by the built-in set() constructor and can be modified afterwards by several methods, such as add().它们由内置的set()构造函数创建,之后可以通过多种方法进行修改,例如add()

Frozen sets冻结集

These represent an immutable set. 这些代表一个不可变的集合。They are created by the built-in frozenset() constructor. 它们由内置的frozenset()构造函数创建。As a frozenset is immutable and hashable, it can be used again as an element of another set, or as a dictionary key.由于冻结集是不可变和可散列的,因此它可以再次用作另一个集合的元素,或者用作字典键。

Mappings映射

These represent finite sets of objects indexed by arbitrary index sets. 这些表示由任意索引集索引的有限对象集。The subscript notation a[k] selects the item indexed by k from the mapping a; this can be used in expressions and as the target of assignments or del statements. 下标符号a[k]从映射a中选择由k索引的项;这可以在表达式中使用,也可以作为赋值或del语句的目标。The built-in function len() returns the number of items in a mapping.内置函数len()返回映射中的项数。

There is currently a single intrinsic mapping type:当前只有一种内部映射类型:

Dictionaries词典

These represent finite sets of objects indexed by nearly arbitrary values. 这些表示由几乎任意值索引的有限对象集。The only types of values not acceptable as keys are values containing lists or dictionaries or other mutable types that are compared by value rather than by object identity, the reason being that the efficient implementation of dictionaries requires a key’s hash value to remain constant. 唯一不能接受作为键的值类型是包含列表或字典或其他可变类型的值,这些值是按值而不是按对象标识进行比较的,原因是字典的有效实现要求键的哈希值保持不变。Numeric types used for keys obey the normal rules for numeric comparison: if two numbers compare equal (e.g., 1 and 1.0) then they can be used interchangeably to index the same dictionary entry.用于键的数字类型遵守数字比较的常规规则:如果两个数字比较相等(例如11.0),则可以互换使用它们来索引相同的字典条目。

Dictionaries preserve insertion order, meaning that keys will be produced in the same order they were added sequentially over the dictionary. 字典保留插入顺序,这意味着键将按照它们在字典上顺序添加的相同顺序生成。Replacing an existing key does not change the order, however removing a key and re-inserting it will add it to the end instead of keeping its old place.替换现有密钥不会改变顺序,但是移除密钥并重新插入它会将其添加到末尾,而不是保留其原来的位置。

Dictionaries are mutable; they can be created by the {...} notation (see section Dictionary displays).字典是可变的;它们可以由{...}创建符号(请参见字典显示一节)。

The extension modules dbm.ndbm and dbm.gnu provide additional examples of mapping types, as does the collections module.扩展模块dbm.ndbmdbm.gnu提供了映射类型的其他示例,集合模块也是如此。

Changed in version 3.7: 在版本3.7中更改:Dictionaries did not preserve insertion order in versions of Python before 3.6. 在3.6之前的Python版本中,字典没有保留插入顺序。In CPython 3.6, insertion order was preserved, but it was considered an implementation detail at that time rather than a language guarantee.在CPython 3.6中,插入顺序被保留下来,但当时它被认为是一个实现细节,而不是语言保证。

Callable types可调用类型

These are the types to which the function call operation (see section Calls) can be applied:以下是可以应用函数调用操作(请参阅调用一节)的类型:

User-defined functions用户定义的函数

A user-defined function object is created by a function definition (see section Function definitions). 用户定义的函数对象由函数定义创建(请参见函数定义一节)。It should be called with an argument list containing the same number of items as the function’s formal parameter list.应使用包含与函数的形式参数列表相同项数的参数列表调用它。

Special attributes:特殊属性:

Attribute属性

Meaning意思

__doc__

The function’s documentation string, or None if unavailable; not inherited by subclasses.函数的文档字符串,如果不可用,则为None;不由子类继承的。

Writable可写的

__name__

The function’s name.函数的名称。

Writable

__qualname__

The function’s qualified name.函数的限定名

New in version 3.3.版本3.3中新增。

Writable

__module__

The name of the module the function was defined in, or None if unavailable.在其中定义函数的模块的名称,如果不可用,则为None

Writable

__defaults__

A tuple containing default argument values for those arguments that have defaults, or None if no arguments have a default value.一个元组,其中包含具有默认值的参数的默认参数值,如果没有参数具有默认值,则为None

Writable

__code__

The code object representing the compiled function body.表示已编译函数体的代码对象。

Writable

__globals__

A reference to the dictionary that holds the function’s global variables — the global namespace of the module in which the function was defined.对保存函数全局变量的字典的引用—定义函数的模块的全局命名空间。

Read-only

__dict__

The namespace supporting arbitrary function attributes.支持任意函数属性的命名空间。

Writable

__closure__

None or a tuple of cells that contain bindings for the function’s free variables. None或包含函数自由变量绑定的单元格元组。See below for information on the cell_contents attribute.有关cell_contents属性的信息,请参阅下文。

Read-only

__annotations__

A dict containing annotations of parameters. 包含参数注释的dict。The keys of the dict are the parameter names, and 'return' for the return annotation, if provided. dict的键是参数名,如果提供,返回注释的键是'return'For more information on working with this attribute, see Annotations Best Practices.有关使用此属性的详细信息,请参阅注释最佳实践

Writable

__kwdefaults__

A dict containing defaults for keyword-only parameters.包含仅关键字参数默认值的dict。

Writable

Most of the attributes labelled “Writable” check the type of the assigned value.大多数标记为“Writable”的属性都会检查赋值的类型。

Function objects also support getting and setting arbitrary attributes, which can be used, for example, to attach metadata to functions. 函数对象还支持获取和设置任意属性,例如,可以使用这些属性将元数据附加到函数。Regular attribute dot-notation is used to get and set such attributes. 常规属性点表示法用于获取和设置此类属性。Note that the current implementation only supports function attributes on user-defined functions. 请注意,当前实现仅支持用户定义函数上的函数属性。Function attributes on built-in functions may be supported in the future.将来可能支持内置函数上的函数属性。

A cell object has the attribute cell_contents. 单元格对象具有属性cell_contentsThis can be used to get the value of the cell, as well as set the value.这可用于获取单元格的值,以及设置值。

Additional information about a function’s definition can be retrieved from its code object; see the description of internal types below. 有关函数定义的其他信息可以从其代码对象中检索;请参见下面的内部类型说明。The cell type can be accessed in the types module.可以在types模块中访问cell类型。

Instance methods实例方法

An instance method object combines a class, a class instance and any callable object (normally a user-defined function).实例方法对象将类、类实例和任何可调用对象(通常是用户定义的函数)组合在一起。

Special read-only attributes: __self__ is the class instance object, __func__ is the function object; __doc__ is the method’s documentation (same as __func__.__doc__); __name__ is the method name (same as __func__.__name__); __module__ is the name of the module the method was defined in, or None if unavailable.特殊只读属性:__self__是类实例对象,__func__是函数对象,__doc__是方法的文档(与__func__.__doc__相同);__name__是方法名称(与__func__.__name__相同);__module__是在其中定义方法的模块的名称,如果不可用,则为None

Methods also support accessing (but not setting) the arbitrary function attributes on the underlying function object.方法还支持访问(但不设置)基础函数对象上的任意函数属性。

User-defined method objects may be created when getting an attribute of a class (perhaps via an instance of that class), if that attribute is a user-defined function object or a class method object.如果某个类的属性是用户定义的函数对象或类方法对象,则可以在获取该类的属性时创建用户定义的方法对象(可能通过该类的实例)。

When an instance method object is created by retrieving a user-defined function object from a class via one of its instances, its __self__ attribute is the instance, and the method object is said to be bound. 当通过一个实例从类中检索用户定义的函数对象来创建实例方法对象时,其__self__属性就是实例,方法对象被称为绑定。The new method’s __func__ attribute is the original function object.新方法的__func__属性是原始函数对象。

When an instance method object is created by retrieving a class method object from a class or instance, its __self__ attribute is the class itself, and its __func__ attribute is the function object underlying the class method.通过从类或实例检索类方法对象来创建实例方法对象时,其__self__属性是类本身,其__func__属性是类方法下面的函数对象。

When an instance method object is called, the underlying function (__func__) is called, inserting the class instance (__self__) in front of the argument list. 调用实例方法对象时,将调用基础函数(__func__),并在参数列表前面插入类实例(__self__)。For instance, when C is a class which contains a definition for a function f(), and x is an instance of C, calling x.f(1) is equivalent to calling C.f(x, 1).例如,当C是一个包含函数f()定义的类,而xC的实例时,调用x.f(1)等同于调用C.f(x, 1)

When an instance method object is derived from a class method object, the “class instance” stored in __self__ will actually be the class itself, so that calling either x.f(1) or C.f(1) is equivalent to calling f(C,1) where f is the underlying function.当实例方法对象派生自类方法对象时,存储在__self__中的“类实例”实际上就是类本身,因此调用x.f(1)C.f(1)相当于调用f(C,1),其中f是基础函数。

Note that the transformation from function object to instance method object happens each time the attribute is retrieved from the instance. 请注意,每次从实例检索属性时,都会发生从函数对象到实例方法对象的转换。In some cases, a fruitful optimization is to assign the attribute to a local variable and call that local variable. 在某些情况下,有效的优化是将属性分配给局部变量并调用该局部变量。Also notice that this transformation only happens for user-defined functions; other callable objects (and all non-callable objects) are retrieved without transformation. 还要注意,这种转换只发生在用户定义的函数中;其他可调用对象(以及所有不可调用对象)将在不进行转换的情况下检索。It is also important to note that user-defined functions which are attributes of a class instance are not converted to bound methods; this only happens when the function is an attribute of the class.还需要注意的是,作为类实例属性的用户定义函数不会转换为绑定方法;只有当函数是类的属性时,才会发生这种情况。

Generator functions生成器函数

A function or method which uses the yield statement (see section The yield statement) is called a generator function. 使用yield语句(参见yield语句一节)的函数或方法称为生成器函数Such a function, when called, always returns an iterator object which can be used to execute the body of the function: calling the iterator’s iterator.__next__() method will cause the function to execute until it provides a value using the yield statement. 这样的函数在调用时总是返回一个迭代器对象,该对象可用于执行函数体:调用迭代器的iterator.__next__()方法将使函数执行,直到它使用yield语句提供值为止。When the function executes a return statement or falls off the end, a StopIteration exception is raised and the iterator will have reached the end of the set of values to be returned.当函数执行return语句或结束时,将引发StopIteration异常,迭代器将到达要返回的值集的末尾。

Coroutine functions协同例程函数

A function or method which is defined using async def is called a coroutine function. 使用async def定义的函数或方法称为协同例程函数Such a function, when called, returns a coroutine object. 这样的函数在调用时返回一个协同例程对象。It may contain await expressions, as well as async with and async for statements. 它可能包含await表达式,以及async with语句和async for语句。See also the Coroutine Objects section.另请参见协同例程对象部分。

Asynchronous generator functions异步生成器函数

A function or method which is defined using async def and which uses the yield statement is called a asynchronous generator function. 使用async def定义并使用yield语句的函数或方法称为异步生成器函数Such a function, when called, returns an asynchronous iterator object which can be used in an async for statement to execute the body of the function.这样的函数在调用时返回一个异步迭代器对象,该对象可在async for语句中用于执行函数体。

Calling the asynchronous iterator’s aiterator.__anext__ method will return an awaitable which when awaited will execute until it provides a value using the yield expression. 调用异步迭代器的aiterator.__anext__方法将返回一个awaitable,等待时将执行它,直到它使用yield表达式提供一个值为止。When the function executes an empty return statement or falls off the end, a StopAsyncIteration exception is raised and the asynchronous iterator will have reached the end of the set of values to be yielded.当函数执行空的return语句或结束时,将引发StopAsyncIteration异常,异步迭代器将到达要生成的值集的末尾。

Built-in functions内置函数

A built-in function object is a wrapper around a C function. 内置函数对象是C函数的包装器。Examples of built-in functions are len() and math.sin() (math is a standard built-in module). 内置函数的示例有len()math.sin()math是标准的内置模块)。The number and type of the arguments are determined by the C function. 参数的数量和类型由C函数确定。Special read-only attributes: __doc__ is the function’s documentation string, or None if unavailable; __name__ is the function’s name; __self__ is set to None (but see the next item); __module__ is the name of the module the function was defined in or None if unavailable.特殊只读属性:__doc__是函数的文档字符串,如果不可用,则为None__name__是函数的名称;__self__设置为None(但请参见下一项);__module__是在其中定义函数的模块的名称,如果不可用,则为None

Built-in methods内置方法

This is really a different disguise of a built-in function, this time containing an object passed to the C function as an implicit extra argument. 这实际上是对内置函数的另一种伪装,这次包含一个作为隐式额外参数传递给C函数的对象。An example of a built-in method is alist.append(), assuming alist is a list object. 内置方法的一个示例是alist.append(),假设alist是列表对象。In this case, the special read-only attribute __self__ is set to the object denoted by alist.在这种情况下,特殊的只读属性__self__被设置为由alist表示的对象。

Classes

Classes are callable. 类是可调用的。These objects normally act as factories for new instances of themselves, but variations are possible for class types that override __new__(). 这些对象通常充当自身新实例的工厂,但重写__new__()的类类型可能会有变化。The arguments of the call are passed to __new__() and, in the typical case, to __init__() to initialize the new instance.调用的参数传递给__new__(),在典型场景中,传递给__init__()以初始化一个新实例。

Class Instances类实例

Instances of arbitrary classes can be made callable by defining a __call__() method in their class.通过在类中定义__call__()方法,可以使任意类的实例可调用。

Modules模块

Modules are a basic organizational unit of Python code, and are created by the import system as invoked either by the import statement, or by calling functions such as importlib.import_module() and built-in __import__(). 模块是Python代码的基本组织单元,由导入系统创建,可以通过import语句调用,也可以通过调用importlib.import_module()和内置的__import__()等函数来调用。A module object has a namespace implemented by a dictionary object (this is the dictionary referenced by the __globals__ attribute of functions defined in the module). 模块对象具有由dictionary对象实现的命名空间(这是由模块中定义的函数的__globals__属性引用的字典)。Attribute references are translated to lookups in this dictionary, e.g., m.x is equivalent to m.__dict__["x"]. 属性引用被转换为此字典中的查找,例如,m.x等效于m.__dict__["x"]A module object does not contain the code object used to initialize the module (since it isn’t needed once the initialization is done).模块对象不包含用于初始化模块的代码对象(因为初始化完成后不需要它)。

Attribute assignment updates the module’s namespace dictionary, e.g., m.x = 1 is equivalent to m.__dict__["x"] = 1.属性赋值更新模块的命名空间字典,例如,m.x = 1相当于m.__dict__["x"] = 1

Predefined (writable) attributes:预定义(可写)属性:

__name__

The module’s name.模块名称。

__doc__

The module’s documentation string, or None if unavailable.模块的文档字符串,如果不可用,则为None

__file__

The pathname of the file from which the module was loaded, if it was loaded from a file. 从中加载模块的文件的路径名(如果从文件加载)。The __file__ attribute may be missing for certain types of modules, such as C modules that are statically linked into the interpreter. 某些类型的模块可能缺少__file__属性,例如静态链接到解释器的C模块。For extension modules loaded dynamically from a shared library, it’s the pathname of the shared library file.对于从共享库动态加载的扩展模块,它是共享库文件的路径名。

__annotations__

A dictionary containing variable annotations collected during module body execution. 包含在模块体执行期间收集的变量注释的字典。For best practices on working with __annotations__, please see Annotations Best Practices.有关使用__annotations__的最佳实践,请参阅注释最佳实践

Special read-only attribute: __dict__ is the module’s namespace as a dictionary object.特殊只读属性:__dict__是模块的命名空间,作为字典对象。

CPython implementation detail:CPython实施详情: Because of the way CPython clears module dictionaries, the module dictionary will be cleared when the module falls out of scope even if the dictionary still has live references. 由于CPython清除模块字典的方式,当模块超出范围时,即使字典仍有活动引用,也会清除模块字典。To avoid this, copy the dictionary or keep the module around while using its dictionary directly.要避免这种情况,请在直接使用其字典时复制字典或保留模块。

Custom classes自定义类

Custom class types are typically created by class definitions (see section Class definitions). 自定义类类型通常由类定义创建(请参见类定义一节)。A class has a namespace implemented by a dictionary object. 类具有由dictionary对象实现的命名空间。Class attribute references are translated to lookups in this dictionary, e.g., C.x is translated to C.__dict__["x"] (although there are a number of hooks which allow for other means of locating attributes). 类属性引用被转换为此字典中的查找,例如,C.x被转换为C.__dict__["x"](尽管有许多挂钩允许使用其他方式定位属性)。When the attribute name is not found there, the attribute search continues in the base classes. 如果在那里找不到属性名称,则在基类中继续进行属性搜索。This search of the base classes uses the C3 method resolution order which behaves correctly even in the presence of ‘diamond’ inheritance structures where there are multiple inheritance paths leading back to a common ancestor. 基类的这种搜索使用C3方法解析顺序,即使在存在“菱形”继承结构的情况下,如果存在多条返回到共同祖先的继承路径,该顺序也会正确运行。Additional details on the C3 MRO used by Python can be found in the documentation accompanying the 2.3 release at https://www.python.org/download/releases/2.3/mro/.有关Python使用的C3 MRO的更多详细信息,请参阅2.3版本附带的文档,网址为https://www.python.org/download/releases/2.3/mro/

When a class attribute reference (for class C, say) would yield a class method object, it is transformed into an instance method object whose __self__ attribute is C. 当一个类属性引用(例如,对于类C)将产生一个类方法对象时,它将被转换为一个实例方法对象,其__self__属性是CWhen it would yield a static method object, it is transformed into the object wrapped by the static method object. 当它将产生一个静态方法对象时,它将被转换为由静态方法对象包装的对象。See section Implementing Descriptors for another way in which attributes retrieved from a class may differ from those actually contained in its __dict__.请参阅实现描述符一节,了解从类中检索到的属性可能不同于其__dict__中实际包含的属性的另一种方式。

Class attribute assignments update the class’s dictionary, never the dictionary of a base class.类属性赋值更新类的字典,而不是基类的字典。

A class object can be called (see above) to yield a class instance (see below).可以调用类对象(见上文)来生成类实例(见下文)。

Special attributes:特殊属性:

__name__

The class name.类名。

__module__

The name of the module in which the class was defined.在其中定义类的模块的名称。

__dict__

The dictionary containing the class’s namespace.包含类的命名空间的字典。

__bases__

A tuple containing the base classes, in the order of their occurrence in the base class list.包含基类的元组,按它们在基类列表中的出现顺序排列。

__doc__

The class’s documentation string, or None if undefined.类的文档字符串,如果未定义,则为None

__annotations__

A dictionary containing variable annotations collected during class body execution. 包含在类主体执行期间收集的变量注释的字典。For best practices on working with __annotations__, please see Annotations Best Practices.有关使用__annotations__的最佳实践,请参阅注释最佳实践

Class instances类实例

A class instance is created by calling a class object (see above). 类实例是通过调用类对象创建的(请参见上文)。A class instance has a namespace implemented as a dictionary which is the first place in which attribute references are searched. 类实例有一个实现为字典的命名空间,字典是搜索属性引用的第一个位置。When an attribute is not found there, and the instance’s class has an attribute by that name, the search continues with the class attributes. 如果在那里找不到属性,并且实例的类具有该名称的属性,则搜索将继续使用类属性。If a class attribute is found that is a user-defined function object, it is transformed into an instance method object whose __self__ attribute is the instance. 如果发现类属性是用户定义的函数对象,则会将其转换为实例方法对象,其__self__属性就是实例。Static method and class method objects are also transformed; see above under “Classes”. 静态方法和类方法对象也被转换;参见上文“类别”下的内容。See section Implementing Descriptors for another way in which attributes of a class retrieved via its instances may differ from the objects actually stored in the class’s __dict__. 请参阅实现描述符一节,了解通过实例检索的类属性与实际存储在类的__dict__中的对象不同的另一种方式。If no class attribute is found, and the object’s class has a __getattr__() method, that is called to satisfy the lookup.如果找不到类属性,并且对象的类有一个__getattr__()方法,则调用该方法以满足查找要求。

Attribute assignments and deletions update the instance’s dictionary, never a class’s dictionary. 属性赋值和删除更新实例的字典,而不是类的字典。If the class has a __setattr__() or __delattr__() method, this is called instead of updating the instance dictionary directly.如果类具有__setattr__()__delattr__()方法,则会调用此方法,而不是直接更新实例字典。

Class instances can pretend to be numbers, sequences, or mappings if they have methods with certain special names. 如果类实例具有具有特定名称的方法,则它们可以假装为数字、序列或映射。See section Special method names.请参阅特殊方法名称一节。

Special attributes: __dict__ is the attribute dictionary; __class__ is the instance’s class.特殊属性:__dict__是属性字典;__class__是实例的类。

I/O objects (also known as file objects)I/O对象(也称为文件对象)

A file object represents an open file. 文件对象表示打开的文件。Various shortcuts are available to create file objects: the open() built-in function, and also os.popen(), os.fdopen(), and the makefile() method of socket objects (and perhaps by other functions or methods provided by extension modules).可以使用各种快捷方式创建文件对象:open()内置函数,以及socket对象的os.popen()os.fdopen()makefile()方法(也可以通过扩展模块提供的其他函数或方法)。

The objects sys.stdin, sys.stdout and sys.stderr are initialized to file objects corresponding to the interpreter’s standard input, output and error streams; they are all open in text mode and therefore follow the interface defined by the io.TextIOBase abstract class.对象sys.stdinsys.stdoutsys.stderr被初始化为与解释器的标准输入、输出和错误流相对应的文件对象;它们都是以文本模式打开的,因此遵循io.TextIOBase抽象类定义的接口。

Internal types内部类型

A few types used internally by the interpreter are exposed to the user. 解释器内部使用的一些类型向用户公开。Their definitions may change with future versions of the interpreter, but they are mentioned here for completeness.它们的定义可能会随着解释器的未来版本而改变,但为了完整性,这里会提到它们。

Code objects代码对象

Code objects represent byte-compiled executable Python code, or bytecode. 代码对象表示字节编译的可执行Python代码或字节码The difference between a code object and a function object is that the function object contains an explicit reference to the function’s globals (the module in which it was defined), while a code object contains no context; also the default argument values are stored in the function object, not in the code object (because they represent values calculated at run-time). 代码对象和函数对象之间的区别在于,函数对象包含对函数全局变量(定义它的模块)的显式引用,而代码对象不包含上下文;此外,默认参数值存储在函数对象中,而不是代码对象中(因为它们表示在运行时计算的值)。Unlike function objects, code objects are immutable and contain no references (directly or indirectly) to mutable objects.与函数对象不同,代码对象是不可变的,不包含对可变对象的引用(直接或间接)。

Special read-only attributes: co_name gives the function name; co_argcount is the total number of positional arguments (including positional-only arguments and arguments with default values); co_posonlyargcount is the number of positional-only arguments (including arguments with default values); co_kwonlyargcount is the number of keyword-only arguments (including arguments with default values); co_nlocals is the number of local variables used by the function (including arguments); co_varnames is a tuple containing the names of the local variables (starting with the argument names); co_cellvars is a tuple containing the names of local variables that are referenced by nested functions; co_freevars is a tuple containing the names of free variables; co_code is a string representing the sequence of bytecode instructions; co_consts is a tuple containing the literals used by the bytecode; co_names is a tuple containing the names used by the bytecode; co_filename is the filename from which the code was compiled; co_firstlineno is the first line number of the function; co_lnotab is a string encoding the mapping from bytecode offsets to line numbers (for details see the source code of the interpreter); co_stacksize is the required stack size; co_flags is an integer encoding a number of flags for the interpreter.特殊只读属性:co_name给出函数名;co_argcount是位置参数的总数(包括仅位置参数和具有默认值的参数);co_posonlyargcount是仅位置参数的数量(包括具有默认值的参数);co_kwonlyargcount是仅关键字参数的数量(包括具有默认值的参数);co_nlocals是函数使用的局部变量数(包括参数);co_varnames是一个元组,包含局部变量的名称(从参数名称开始);co_cellvars是一个元组,包含嵌套函数引用的局部变量的名称;co_freevars是一个包含自由变量名称的元组;co_code是表示字节码指令序列的字符串;co_consts是一个元组,包含字节码使用的文本;co_names是一个元组,包含字节码使用的名称;co_filename是编译代码的文件名;co_firstlineno是函数的第一行号;co_lnotab是一个字符串,用于编码从字节码偏移量到行号的映射(有关详细信息,请参阅解释器的源代码);co_stacksize是所需的堆栈大小;co_flags是一个整数,为解释器编码了许多标志。

The following flag bits are defined for co_flags: bit 0x04 is set if the function uses the *arguments syntax to accept an arbitrary number of positional arguments; bit 0x08 is set if the function uses the **keywords syntax to accept arbitrary keyword arguments; bit 0x20 is set if the function is a generator.co_flags定义了以下标志位:如果函数使用*arguments语法接受任意数量的位置参数,则设置位0x04;如果函数使用**keywords语法接受任意关键字参数,则设置位0x08;如果函数为生成器,则设置位0x20

Future feature declarations (from __future__ import division) also use bits in co_flags to indicate whether a code object was compiled with a particular feature enabled: bit 0x2000 is set if the function was compiled with future division enabled; bits 0x10 and 0x1000 were used in earlier versions of Python.未来功能声明(来自from __future__ import division)还使用co_flags中的位来指示代码对象是否在启用特定功能的情况下编译:如果函数在启用未来分区的情况下编译,则设置位0x2000;位0x100x1000在早期版本的Python中使用。

Other bits in co_flags are reserved for internal use.co_flags中的其他位保留供内部使用。

If a code object represents a function, the first item in co_consts is the documentation string of the function, or None if undefined.如果代码对象表示函数,则co_consts中的第一项是函数的文档字符串,如果未定义,则为None

Frame objects框架对象

Frame objects represent execution frames. 帧对象表示执行帧。They may occur in traceback objects (see below), and are also passed to registered trace functions.它们可能出现在回溯对象中(见下文),也会传递给已注册的跟踪函数。

Special read-only attributes: f_back is to the previous stack frame (towards the caller), or None if this is the bottom stack frame; f_code is the code object being executed in this frame; f_locals is the dictionary used to look up local variables; f_globals is used for global variables; f_builtins is used for built-in (intrinsic) names; f_lasti gives the precise instruction (this is an index into the bytecode string of the code object).特殊只读属性:f_back是上一个堆栈帧(朝向调用者),如果这是底部堆栈帧,则为Nonef_code是在此帧中执行的代码对象;f_locals是用来查找局部变量的字典;f_globals用于全局变量;f_builtins用于内置(固有)名称;f_lasti给出了精确的指令(这是代码对象字节码字符串的索引)。

Accessing f_code raises an auditing event object.__getattr__ with arguments obj and "f_code".访问f_code会引发审核事件object.__getattr__,参数为obj"f_code"

Special writable attributes: f_trace, if not None, is a function called for various events during code execution (this is used by the debugger). 特殊可写属性:f_trace(如果不是None)是在代码执行期间为各种事件调用的函数(调试器使用)。Normally an event is triggered for each new source line - this can be disabled by setting f_trace_lines to False.通常会为每个新的源行触发一个事件-可以通过将f_trace_lines设置为False来禁用此功能。

Implementations may allow per-opcode events to be requested by setting f_trace_opcodes to True. 通过将f_trace_opcodes设置为True,实现可能允许请求每操作码事件。Note that this may lead to undefined interpreter behaviour if exceptions raised by the trace function escape to the function being traced.请注意,如果跟踪函数引发的异常转义到被跟踪的函数,这可能会导致未定义的解释器行为。

f_lineno is the current line number of the frame — writing to this from within a trace function jumps to the given line (only for the bottom-most frame). 是帧的当前行号:从跟踪函数中写入该行会跳到给定行(仅适用于最底部的帧)。A debugger can implement a Jump command (aka Set Next Statement) by writing to f_lineno.调试器可以通过写入f_lineno来实现跳转命令(也称为Set Next语句)。

Frame objects support one method:框架对象支持一种方法:

frame.clear()

This method clears all references to local variables held by the frame. 此方法清除对框架持有的局部变量的所有引用。Also, if the frame belonged to a generator, the generator is finalized. 此外,如果框架属于生成器,则生成器将最终确定。This helps break reference cycles involving frame objects (for example when catching an exception and storing its traceback for later use).这有助于打破涉及框架对象的引用循环(例如,捕获异常并存储其回溯以供以后使用时)。

RuntimeError is raised if the frame is currently executing.如果当前正在执行帧,则引发。

New in version 3.4.版本3.4中新增。

Traceback objects回溯对象

Traceback objects represent a stack trace of an exception. 回溯对象表示异常的堆栈跟踪。A traceback object is implicitly created when an exception occurs, and may also be explicitly created by calling types.TracebackType.当发生异常时,将隐式创建回溯对象,也可以通过调用types.TracebackType显式创建回溯对象。

For implicitly created tracebacks, when the search for an exception handler unwinds the execution stack, at each unwound level a traceback object is inserted in front of the current traceback. 对于隐式创建的回溯,当搜索异常处理程序展开执行堆栈时,在每个展开级别,将在当前回溯之前插入一个回溯对象。When an exception handler is entered, the stack trace is made available to the program. 当输入异常处理程序时,堆栈跟踪对程序可用。(See section The try statement.) (请参阅try语句一节。)It is accessible as the third item of the tuple returned by sys.exc_info(), and as the __traceback__ attribute of the caught exception.它可以作为sys.exc_info()返回的元组的第三项访问,也可以作为捕获的异常的__traceback__属性访问。

When the program contains no suitable handler, the stack trace is written (nicely formatted) to the standard error stream; if the interpreter is interactive, it is also made available to the user as sys.last_traceback.当程序不包含合适的处理程序时,堆栈跟踪将写入(格式良好)标准错误流;如果解释器是交互式的,那么它也可以作为sys.last_traceback提供给用户。

For explicitly created tracebacks, it is up to the creator of the traceback to determine how the tb_next attributes should be linked to form a full stack trace.对于显式创建的回溯,由回溯的创建者决定如何链接tb_next属性以形成完整的堆栈跟踪。

Special read-only attributes: tb_frame points to the execution frame of the current level; tb_lineno gives the line number where the exception occurred; tb_lasti indicates the precise instruction. 特殊只读属性:tb_frame指向当前级别的执行帧;tb_lineno给出发生异常的行号;tb_lasti表示精确的指令。The line number and last instruction in the traceback may differ from the line number of its frame object if the exception occurred in a try statement with no matching except clause or with a finally clause.如果异常发生在没有匹配except子句或使用finally子句的try语句中,则回溯中的行号和最后一条指令可能与其帧对象的行号不同。

Accessing tb_frame raises an auditing event object.__getattr__ with arguments obj and "tb_frame".访问tb_frame会引发审核事件object.__getattr__,参数为obj"tb_frame"

Special writable attribute: tb_next is the next level in the stack trace (towards the frame where the exception occurred), or None if there is no next level.特殊可写属性:tb_next是堆栈跟踪中的下一级(指向发生异常的帧),如果没有下一级,则为None

Changed in version 3.7:版本3.7中更改: Traceback objects can now be explicitly instantiated from Python code, and the tb_next attribute of existing instances can be updated.现在可以从Python代码显式实例化回溯对象,并且可以更新现有实例的tb_next属性。

Slice objects切片对象

Slice objects are used to represent slices for __getitem__() methods. 切片对象用于表示__getitem__()方法的切片。They are also created by the built-in slice() function.它们也由内置的slice()函数创建。

Special read-only attributes: start is the lower bound; stop is the upper bound; step is the step value; each is None if omitted. 特殊只读属性:start为下限;stop是上限;step是步长值;如果省略,每个都是NoneThese attributes can have any type.这些属性可以有任何类型。

Slice objects support one method:切片对象支持一种方法:

slice.indices(self, length)

This method takes a single integer argument length and computes information about the slice that the slice object would describe if applied to a sequence of length items. 此方法采用单个整数参数length,并计算有关切片的信息,如果应用于length项序列,则切片对象将描述该切片。It returns a tuple of three integers; respectively these are the start and stop indices and the step or stride length of the slice. 它返回三个整数的元组;这些分别是startstop索引以及片段的step或步幅。Missing or out-of-bounds indices are handled in a manner consistent with regular slices.缺失或越界索引的处理方式与常规切片一致。

Static method objects静态方法对象

Static method objects provide a way of defeating the transformation of function objects to method objects described above. 静态方法对象提供了一种阻止函数对象向上述方法对象转换的方法。A static method object is a wrapper around any other object, usually a user-defined method object. 静态方法对象是任何其他对象的包装,通常是用户定义的方法对象。When a static method object is retrieved from a class or a class instance, the object actually returned is the wrapped object, which is not subject to any further transformation. 当从类或类实例检索静态方法对象时,实际返回的对象是包装对象,它不受任何进一步转换的约束。Static method objects are also callable. 静态方法对象也可以调用。Static method objects are created by the built-in staticmethod() constructor.静态方法对象由内置的staticmethod()构造函数创建。

Class method objects类方法对象

A class method object, like a static method object, is a wrapper around another object that alters the way in which that object is retrieved from classes and class instances. 与静态方法对象一样,类方法对象是另一个对象的包装器,它改变了从类和类实例检索该对象的方式。The behaviour of class method objects upon such retrieval is described above, under “User-defined methods”. 上述“用户定义方法”下描述了此类检索时类方法对象的行为。Class method objects are created by the built-in classmethod() constructor.类方法对象由内置的classmethod()构造函数创建。

3.3. Special method names特殊方法名称

A class can implement certain operations that are invoked by special syntax (such as arithmetic operations or subscripting and slicing) by defining methods with special names. 类可以通过定义具有特殊名称的方法来实现由特殊语法调用的某些操作(如算术运算或订阅和切片)。This is Python’s approach to operator overloading, allowing classes to define their own behavior with respect to language operators. 这是Python的运算符重载方法,允许类定义它们自己关于语言运算符的行为。For instance, if a class defines a method named __getitem__(), and x is an instance of this class, then x[i] is roughly equivalent to type(x).__getitem__(x, i). 例如,如果一个类定义了一个名为__getitem__()的方法,并且x是这个类的实例,那么x[i]大致相当于type(x).__getitem__(x, i)Except where mentioned, attempts to execute an operation raise an exception when no appropriate method is defined (typically AttributeError or TypeError).除非另有说明,否则在未定义适当的方法(通常是AttributeErrorTypeError)时,尝试执行操作会引发异常。

Setting a special method to None indicates that the corresponding operation is not available. 将特殊方法设置为None表示相应的操作不可用。For example, if a class sets __iter__() to None, the class is not iterable, so calling iter() on its instances will raise a TypeError (without falling back to __getitem__()). 例如,如果一个类将__iter__()设置为None,则该类是不可迭代的,因此对其实例调用iter()将引发TypeError(而不会回退到__getitem__())。2

When implementing a class that emulates any built-in type, it is important that the emulation only be implemented to the degree that it makes sense for the object being modelled. 当实现一个模拟任何内置类型的类时,重要的是,模拟的实现必须达到对建模对象有意义的程度。For example, some sequences may work well with retrieval of individual elements, but extracting a slice may not make sense. 例如,某些序列可以很好地检索单个元素,但提取切片可能没有意义。(One example of this is the NodeList interface in the W3C’s Document Object Model.)(W3C文档对象模型中的NodeList接口就是一个例子。)

3.3.1. Basic customization基本自定义

object.__new__(cls[, ...])

Called to create a new instance of class cls. 调用以创建类cls的新实例。__new__() is a static method (special-cased so you need not declare it as such) that takes the class of which an instance was requested as its first argument. 是一个静态方法(特殊情况下,您无需将其声明为特殊情况),它将请求实例的类作为其第一个参数。The remaining arguments are those passed to the object constructor expression (the call to the class). 其余的参数是传递给对象构造函数表达式(对类的调用)的参数。The return value of __new__() should be the new object instance (usually an instance of cls).__new__()的返回值应该是新对象实例(通常是cls的实例)。

Typical implementations create a new instance of the class by invoking the superclass’s __new__() method using super().__new__(cls[, ...]) with appropriate arguments and then modifying the newly-created instance as necessary before returning it.典型的实现通过使用super().__new__(cls[, ...])调用超类的__new__()方法,使用适当的参数,来创建类的新实例,然后根据需要修改新创建的实例,然后再返回它。

If __new__() is invoked during object construction and it returns an instance of cls, then the new instance’s __init__() method will be invoked like __init__(self[, ...]), where self is the new instance and the remaining arguments are the same as were passed to the object constructor.如果在对象构造过程中调用了__new__()并返回cls实例,则将像调用__init__(self[, ...])一样调用新实例的__init__()方法,其中self是新实例,其余参数与传递给对象构造函数的参数相同。

If __new__() does not return an instance of cls, then the new instance’s __init__() method will not be invoked.如果__new__()未返回cls实例,则不会调用新实例的__init__()方法。

__new__() is intended mainly to allow subclasses of immutable types (like int, str, or tuple) to customize instance creation. 主要用于允许不可变类型的子类(如int、str或tuple)自定义实例创建。It is also commonly overridden in custom metaclasses in order to customize class creation.为了自定义类的创建,它通常在自定义元类中被重写。

object.__init__(self[, ...])

Called after the instance has been created (by __new__()), but before it is returned to the caller. 在实例创建之后(由__new__())调用,但在实例返回给调用方之前调用。The arguments are those passed to the class constructor expression. 参数是传递给类构造函数表达式的参数。If a base class has an __init__() method, the derived class’s __init__() method, if any, must explicitly call it to ensure proper initialization of the base class part of the instance; for example: super().__init__([args...]).如果基类具有__init__()方法,则派生类的__init__()方法(如果有)必须显式调用它,以确保正确初始化实例的基类部分;例如:super().__init__([args...])

Because __new__() and __init__() work together in constructing objects (__new__() to create it, and __init__() to customize it), no non-None value may be returned by __init__(); doing so will cause a TypeError to be raised at runtime.由于__new__()__init__()在构造对象时协同工作(__new__()创建对象,而__init__()自定义对象),因此__init__()不能返回非None值;这样做将导致在运行时引发TypeError

object.__del__(self)

Called when the instance is about to be destroyed. 在实例即将销毁时调用。This is also called a finalizer or (improperly) a destructor. 这也称为终结器或(不适当地)析构函数。If a base class has a __del__() method, the derived class’s __del__() method, if any, must explicitly call it to ensure proper deletion of the base class part of the instance.如果基类具有__del__()方法,则派生类的__del__()方法(如果有)必须显式调用它,以确保正确删除实例的基类部分。

It is possible (though not recommended!) for the __del__() method to postpone destruction of the instance by creating a new reference to it. 对于__del__()方法,可以(尽管不推荐!)通过创建对实例的新引用来推迟实例的销毁。This is called object resurrection. 这叫做对象“复活”。It is implementation-dependent whether __del__() is called a second time when a resurrected object is about to be destroyed; the current CPython implementation only calls it once.当复活的对象即将被销毁时,是否再次调用__del__()取决于实现;当前的CPython实现只调用它一次。

It is not guaranteed that __del__() methods are called for objects that still exist when the interpreter exits.当解释器退出时,不能保证为仍然存在的对象调用__del__()方法。

Note

del x doesn’t directly call x.__del__() — the former decrements the reference count for x by one, and the latter is only called when x’s reference count reaches zero.del x不直接调用x.__del__():前者将x的引用计数递减1,后者仅在x的引用计数为零时调用。

CPython implementation detail:CPython实施详情: It is possible for a reference cycle to prevent the reference count of an object from going to zero. 引用循环可以防止对象的引用计数变为零。In this case, the cycle will be later detected and deleted by the cyclic garbage collector. 在这种情况下,循环垃圾回收器稍后将检测并删除该循环。A common cause of reference cycles is when an exception has been caught in a local variable. 引用循环的一个常见原因是在局部变量中捕获到异常。The frame’s locals then reference the exception, which references its own traceback, which references the locals of all frames caught in the traceback.然后,帧的局部变量引用异常,该异常引用其自身的回溯,该回溯引用在回溯中捕获的所有帧的局部变量。

See also参阅

Documentation for the gc module.gc模块的文档。

Warning

Due to the precarious circumstances under which __del__() methods are invoked, exceptions that occur during their execution are ignored, and a warning is printed to sys.stderr instead. 由于调用__del__()方法的情况不稳定,在执行过程中发生的异常将被忽略,而会向sys.stderr打印一条警告。In particular:

  • __del__() can be invoked when arbitrary code is being executed, including from any arbitrary thread. 可以在执行任意代码时调用,包括从任意线程执行。If __del__() needs to take a lock or invoke any other blocking resource, it may deadlock as the resource may already be taken by the code that gets interrupted to execute __del__().如果__del__()需要获取锁或调用任何其他阻塞资源,它可能会死锁,因为该资源可能已被中断以执行__del__()的代码获取。

  • __del__() can be executed during interpreter shutdown. 可以在解释器关闭期间执行。As a consequence, the global variables it needs to access (including other modules) may already have been deleted or set to None. 因此,它需要访问的全局变量(包括其他模块)可能已经被删除或设置为NonePython guarantees that globals whose name begins with a single underscore are deleted from their module before other globals are deleted; if no other references to such globals exist, this may help in assuring that imported modules are still available at the time when the __del__() method is called.Python保证在删除其他全局变量之前,从其模块中删除名称以单个下划线开头的全局变量;如果不存在对此类全局变量的其他引用,这可能有助于确保导入的模块在调用__del__()方法时仍然可用。

object.__repr__(self)

Called by the repr() built-in function to compute the “official” string representation of an object. repr()内置函数调用,以计算对象的“正式”字符串表示形式。If at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value (given an appropriate environment). 如果可能的话,这应该看起来像一个有效的Python表达式,可以用来重新创建具有相同值的对象(给定适当的环境)。If this is not possible, a string of the form <...some useful description...> should be returned. 如果这是不可能的,则应返回形式为<...some useful description...>的字符串。The return value must be a string object. 返回值必须是字符串对象。If a class defines __repr__() but not __str__(), then __repr__() is also used when an “informal” string representation of instances of that class is required.如果一个类定义了__repr__(),但没有定义__str__(),那么当需要该类实例的“非正式”字符串表示时,也会使用__repr__()

This is typically used for debugging, so it is important that the representation is information-rich and unambiguous.这通常用于调试,因此表示形式必须信息丰富且明确。

object.__str__(self)

Called by str(object) and the built-in functions format() and print() to compute the “informal” or nicely printable string representation of an object. str(object)和内置函数format()print()调用,以计算对象的“非正式”或可良好打印的字符串表示形式。The return value must be a string object.返回值必须是字符串对象。

This method differs from object.__repr__() in that there is no expectation that __str__() return a valid Python expression: a more convenient or concise representation can be used.此方法与object.__repr__()不同,因为不期望__str__()返回有效的Python表达式:可以使用更方便或简洁的表示。

The default implementation defined by the built-in type object calls object.__repr__().由内置类型object定义的默认实现调用object.__repr__()

object.__bytes__(self)

Called by bytes to compute a byte-string representation of an object. 字节调用以计算对象的字节字符串表示形式。This should return a bytes object.这将返回一个bytes对象。

object.__format__(self, format_spec)

Called by the format() built-in function, and by extension, evaluation of formatted string literals and the str.format() method, to produce a “formatted” string representation of an object. format()内置函数调用,并扩展为对格式化字符串文本的求值和str.format()方法,以生成对象的“格式化”字符串表示。The format_spec argument is a string that contains a description of the formatting options desired. format_spec参数是一个字符串,包含所需格式选项的描述。The interpretation of the format_spec argument is up to the type implementing __format__(), however most classes will either delegate formatting to one of the built-in types, or use a similar formatting option syntax.format_spec参数的解释取决于实现__format__()的类型,但是大多数类要么将格式委托给其中一个内置类型,要么使用类似的格式选项语法。

See Format Specification Mini-Language for a description of the standard formatting syntax.有关标准格式语法的描述,请参阅格式规范迷你语言

The return value must be a string object.返回值必须是字符串对象。

Changed in version 3.4:版本3.4中更改: The __format__ method of object itself raises a TypeError if passed any non-empty string.如果传递了任何非空字符串,object本身的__format__方法将引发TypeError

Changed in version 3.7:版本3.7中更改: object.__format__(x, '') is now equivalent to str(x) rather than format(str(x), '').现在等效于str(x),而不是format(str(x), '')

object.__lt__(self, other)
object.__le__(self, other)
object.__eq__(self, other)
object.__ne__(self, other)
object.__gt__(self, other)
object.__ge__(self, other)

These are the so-called “rich comparison” methods. 这些就是所谓的“丰富比较”方法。The correspondence between operator symbols and method names is as follows: x<y calls x.__lt__(y), x<=y calls x.__le__(y), x==y calls x.__eq__(y), x!=y calls x.__ne__(y), x>y calls x.__gt__(y), and x>=y calls x.__ge__(y).运算符符号和方法名称之间的对应关系如下:x<y调用x.__lt__(y)x<=y调用x.__le__(y)x==y调用x.__eq__(y)x!=y调用x.__ne__(y)x>y调用x.__le__(y)x>=y调用x.__ge__(y)

A rich comparison method may return the singleton NotImplemented if it does not implement the operation for a given pair of arguments. 如果富比较方法没有为给定的一对参数实现操作,则它可能返回singleton NotImplementedBy convention, False and True are returned for a successful comparison. 按照惯例,将返回FalseTrue以进行成功的比较。However, these methods can return any value, so if the comparison operator is used in a Boolean context (e.g., in the condition of an if statement), Python will call bool() on the value to determine if the result is true or false.但是,这些方法可以返回任何值,因此如果在布尔上下文中使用比较运算符(例如,在if语句的条件下),Python将对该值调用bool(),以确定结果是真还是假。

By default, object implements __eq__() by using is, returning NotImplemented in the case of a false comparison: True if x is y else NotImplemented. 默认情况下,object通过使用is实现__eq__(),如果比较错误,则返回NotImplementedTrue if x is y else NotImplementedFor __ne__(), by default it delegates to __eq__() and inverts the result unless it is NotImplemented. 对于__ne__(),默认情况下,它委托给__eq__(),并反转结果,除非它是NotImplementedThere are no other implied relationships among the comparison operators or default implementations; for example, the truth of (x<y or x==y) does not imply x<=y. 比较运算符或默认实现之间没有其他隐含关系;例如,(x<y or x==y)的真值并不意味着x<=yTo automatically generate ordering operations from a single root operation, see functools.total_ordering().要从单个根操作自动生成排序操作,请参阅functools.total_ordering()

See the paragraph on __hash__() for some important notes on creating hashable objects which support custom comparison operations and are usable as dictionary keys.有关创建支持自定义比较操作并可用作字典键的可哈希对象的一些重要说明,请参阅__hash__()一段。

There are no swapped-argument versions of these methods (to be used when the left argument does not support the operation but the right argument does); rather, __lt__() and __gt__() are each other’s reflection, __le__() and __ge__() are each other’s reflection, and __eq__() and __ne__() are their own reflection. 这些方法没有交换的参数版本(当左参数不支持该操作,但右参数支持该操作时使用);但是,__lt__()__gt__()各为对方的反射,__le__()__ge__()各为对方的反射,__eq__()__ne__()是它们自己的反射。If the operands are of different types, and right operand’s type is a direct or indirect subclass of the left operand’s type, the reflected method of the right operand has priority, otherwise the left operand’s method has priority. 如果操作数的类型不同,并且右操作数的类型是左操作数类型的直接或间接子类,则右操作数的反射方法具有优先级,否则左操作数的方法具有优先级。Virtual subclassing is not considered.不考虑虚拟子类化。

object.__hash__(self)

Called by built-in function hash() and for operations on members of hashed collections including set, frozenset, and dict. 由内置函数hash()调用,并用于对哈希集合(包括setfrozensetdict)的成员执行操作。The __hash__() method should return an integer. __hash__()方法应返回一个整数。The only required property is that objects which compare equal have the same hash value; it is advised to mix together the hash values of the components of the object that also play a part in comparison of objects by packing them into a tuple and hashing the tuple. 唯一需要的属性是比较相等的对象具有相同的哈希值;建议将对象组件的哈希值混合在一起,通过将它们打包到一个元组中并对元组进行哈希处理,这些组件也在对象的比较中发挥作用。Example:例如:

def __hash__(self):
return hash((self.name, self.nick, self.color))

Note

hash() truncates the value returned from an object’s custom __hash__() method to the size of a Py_ssize_t. 将从对象的自定义__hash__()方法返回的值截断为Py_ssize_t的大小。This is typically 8 bytes on 64-bit builds and 4 bytes on 32-bit builds. 在64位构建中,这通常是8个字节,在32位构建中是4个字节。If an object’s __hash__() must interoperate on builds of different bit sizes, be sure to check the width on all supported builds. 如果对象的__hash__()必须在不同位大小的生成上进行互操作,请确保检查所有支持的生成上的宽度。An easy way to do this is with python -c "import sys; print(sys.hash_info.width)".一种简单的方法是使用python -c "import sys; print(sys.hash_info.width)"

If a class does not define an __eq__() method it should not define a __hash__() operation either; if it defines __eq__() but not __hash__(), its instances will not be usable as items in hashable collections. 如果一个类没有定义__eq__()方法,那么它也不应该定义__hash__()操作;如果它定义了__eq__(),但没有定义__hash__(),则其实例将无法用作可哈希集合中的项。If a class defines mutable objects and implements an __eq__() method, it should not implement __hash__(), since the implementation of hashable collections requires that a key’s hash value is immutable (if the object’s hash value changes, it will be in the wrong hash bucket).如果类定义可变对象并实现__eq__()方法,则不应实现__hash__(),因为可哈希集合的实现要求键的哈希值是不可变的(如果对象的哈希值更改,则它将位于错误的哈希桶中)。

User-defined classes have __eq__() and __hash__() methods by default; with them, all objects compare unequal (except with themselves) and x.__hash__() returns an appropriate value such that x == y implies both that x is y and hash(x) == hash(y).默认情况下,用户定义的类有__eq__()__hash__()方法;使用它们,所有对象都比较不相等(除了它们自己),并且x.__hash__()返回一个适当的值,使得x==y意味着x is y,而hash(x) == hash(y)

A class that overrides __eq__() and does not define __hash__() will have its __hash__() implicitly set to None. 重写__eq__()且未定义__hash__()的类将其__hash__()隐式设置为NoneWhen the __hash__() method of a class is None, instances of the class will raise an appropriate TypeError when a program attempts to retrieve their hash value, and will also be correctly identified as unhashable when checking isinstance(obj, collections.abc.Hashable).当类的__hash__()方法为None时,当程序尝试检索其哈希值时,该类的实例将引发相应的TypeError,并且在检查isinstance(obj, collections.abc.Hashable)时,该类的实例也将被正确标识为不可损坏。

If a class that overrides __eq__() needs to retain the implementation of __hash__() from a parent class, the interpreter must be told this explicitly by setting __hash__ = <ParentClass>.__hash__.如果重写__eq__()的类需要从父类保留__hash__()的实现,则必须通过设置__hash__ = <ParentClass>.__hash__,明确告知解释器这一点。

If a class that does not override __eq__() wishes to suppress hash support, it should include __hash__ = None in the class definition. 如果未重写__eq__()的类希望取消哈希支持,则应在类定义中包含__hash__ = NoneA class which defines its own __hash__() that explicitly raises a TypeError would be incorrectly identified as hashable by an isinstance(obj, collections.abc.Hashable) call.一个定义了自有的__hash__()以显式引发TypeError的类会被isinstance(obj, collections.abc.Hashable)调用错误地识别为可哈希对象。

Note

By default, the __hash__() values of str and bytes objects are “salted” with an unpredictable random value. 默认情况下,str和bytes对象的__hash__()值是用不可预测的随机值“salt”的。Although they remain constant within an individual Python process, they are not predictable between repeated invocations of Python.虽然它们在单个Python进程中保持不变,但在重复调用Python之间是不可预测的。

This is intended to provide protection against a denial-of-service caused by carefully-chosen inputs that exploit the worst case performance of a dict insertion, O(n2) complexity. 这是为了提供保护,防止由于精心选择的输入导致的拒绝服务,这些输入利用dict插入的最坏情况性能,O(n2)复杂性。See http://www.ocert.org/advisories/ocert-2011-003.html for details.有关详细信息请参阅http://www.ocert.org/advisories/ocert-2011-003.html

Changing hash values affects the iteration order of sets. 更改哈希值会影响集合的迭代顺序。Python has never made guarantees about this ordering (and it typically varies between 32-bit and 64-bit builds).Python从未保证过这种排序(通常在32位和64位构建之间有所不同)。

See also PYTHONHASHSEED.另请参见PYTHONHASHSEED

Changed in version 3.3:版本3.3中更改: Hash randomization is enabled by default.默认情况下启用哈希随机化。

object.__bool__(self)

Called to implement truth value testing and the built-in operation bool(); should return False or True. 调用以实现真值测试和内置操作bool();应返回FalseTrueWhen this method is not defined, __len__() is called, if it is defined, and the object is considered true if its result is nonzero. 未定义此方法时,如果已定义,则调用__len__(),如果结果为非零,则认为该对象为trueIf a class defines neither __len__() nor __bool__(), all its instances are considered true.如果一个类既不定义__len__()也不定义__bool__(),则其所有实例都被视为true

3.3.2. Customizing attribute access自定义属性访问

The following methods can be defined to customize the meaning of attribute access (use of, assignment to, or deletion of x.name) for class instances.可以定义以下方法来自定义类实例的属性访问(使用、分配或删除x.name)的含义。

object.__getattr__(self, name)

Called when the default attribute access fails with an AttributeError (either __getattribute__() raises an AttributeError because name is not an instance attribute or an attribute in the class tree for self; or __get__() of a name property raises AttributeError). 当默认属性访问失败并出现AttributeError时调用(要么因为name不是实例属性,或者因为name不是类树中的self属性,导致__getattribute__()引发AttributeError;或name属性的__get__()引发AttributeError)。This method should either return the (computed) attribute value or raise an AttributeError exception.此方法应返回(计算的)属性值或引发AttributeError异常。

Note that if the attribute is found through the normal mechanism, __getattr__() is not called. 请注意,如果通过正常机制找到该属性,则不会调用__getattr__()(This is an intentional asymmetry between __getattr__() and __setattr__().) (这是__getattr__()__setattr__()之间有意的不对称。)This is done both for efficiency reasons and because otherwise __getattr__() would have no way to access other attributes of the instance. 这样做是出于效率原因,也因为否则__getattr__()将无法访问实例的其他属性。Note that at least for instance variables, you can fake total control by not inserting any values in the instance attribute dictionary (but instead inserting them in another object). 请注意,至少对于实例变量,您可以通过不在实例属性字典中插入任何值(而是在另一个对象中插入值)来伪造总控制。See the __getattribute__() method below for a way to actually get total control over attribute access.请参阅下面的__getattribute__()方法,以获得对属性访问的完全控制。

object.__getattribute__(self, name)

Called unconditionally to implement attribute accesses for instances of the class. 无条件调用以实现类实例的属性访问。If the class also defines __getattr__(), the latter will not be called unless __getattribute__() either calls it explicitly or raises an AttributeError. 如果类还定义了__getattr__(),后者不会被调用,除非__getattribute__()也显式调用了它,否则会引发AttributeErrorThis method should return the (computed) attribute value or raise an AttributeError exception. 此方法应返回(计算的)属性值或引发AttributeError异常。In order to avoid infinite recursion in this method, its implementation should always call the base class method with the same name to access any attributes it needs, for example, object.__getattribute__(self, name).为了避免此方法中的无限递归,其实现应该始终使用相同的名称调用基类方法来访问它所需的任何属性,例如object.__getattribute__(self, name)

Note

This method may still be bypassed when looking up special methods as the result of implicit invocation via language syntax or built-in functions. 当通过语言语法或内置函数隐式调用查找特殊方法时,仍然可以绕过此方法。See Special method lookup.请参见特殊方法查找

For certain sensitive attribute accesses, raises an auditing event object.__getattr__ with arguments obj and name.对于某些敏感属性访问,引发审核事件object.__getattr__,参数为objname

object.__setattr__(self, name, value)

Called when an attribute assignment is attempted. 尝试指定属性时调用。This is called instead of the normal mechanism (i.e. store the value in the instance dictionary). 它被调用,而不是正常的机制(即,将值存储在实例字典中)。name is the attribute name, value is the value to be assigned to it.name是属性名称,value是要分配给它的值。

If __setattr__() wants to assign to an instance attribute, it should call the base class method with the same name, for example, object.__setattr__(self, name, value).如果__setattr__()想要分配给实例属性,它应该调用具有相同名称的基类方法,例如object.__setattr__(self, name, value)

For certain sensitive attribute assignments, raises an auditing event object.__setattr__ with arguments obj, name, value.对于某些敏感属性分配,引发审核事件object.__setattr__,参数为objnamevalue

object.__delattr__(self, name)

Like __setattr__() but for attribute deletion instead of assignment. 类似于__setattr__(),但用于属性删除而不是赋值。This should only be implemented if del obj.name is meaningful for the object.只有当del obj.name对对象有意义时,才应该实现这一点。

For certain sensitive attribute deletions, raises an auditing event object.__delattr__ with arguments obj and name.对于某些敏感属性删除,引发审核事件object.__delattr__,参数为objname

object.__dir__(self)

Called when dir() is called on the object. 在对象上调用dir()时调用。A sequence must be returned. 必须返回序列。dir() converts the returned sequence to a list and sorts it.dir()将返回的序列转换为列表并对其排序。

3.3.2.1. Customizing module attribute access自定义模块属性访问

Special names __getattr__ and __dir__ can be also used to customize access to module attributes. 特殊名称__getattr____dir__也可用于自定义对模块属性的访问。The __getattr__ function at the module level should accept one argument which is the name of an attribute and return the computed value or raise an AttributeError. 模块级的__getattr__函数应接受一个作为属性名称的参数,并返回计算值或引发AttributeErrorIf an attribute is not found on a module object through the normal lookup, i.e. object.__getattribute__(), then __getattr__ is searched in the module __dict__ before raising an AttributeError. 如果通过常规查找在模块对象上找不到属性,即对象object.__getattribute__(),然后在引发AttributeError之前,在模块__dict__搜索__getattr__If found, it is called with the attribute name and the result is returned.如果找到,将使用属性名称调用它,并返回结果。

The __dir__ function should accept no arguments, and return a sequence of strings that represents the names accessible on module. __dir__函数不应接受任何参数,并返回一系列字符串,这些字符串表示模块上可访问的名称。If present, this function overrides the standard dir() search on a module.如果存在,此函数将覆盖模块上的标准dir()搜索。

For a more fine grained customization of the module behavior (setting attributes, properties, etc.), one can set the __class__ attribute of a module object to a subclass of types.ModuleType. 为了更细粒度地定制模块行为(设置属性、属性等),可以将模块对象的__class__属性设置为types.ModuleType的子类。For example:例如:

import sys
from types import ModuleType
class VerboseModule(ModuleType):
def __repr__(self):
return f'Verbose {self.__name__}'

def __setattr__(self, attr, value):
print(f'Setting {attr}...')
super().__setattr__(attr, value)

sys.modules[__name__].__class__ = VerboseModule

Note

Defining module __getattr__ and setting module __class__ only affect lookups made using the attribute access syntax – directly accessing the module globals (whether by code within the module, or via a reference to the module’s globals dictionary) is unaffected.定义模块__getattr__设置模块__class__仅影响使用属性访问语法进行的查找-直接访问模块全局变量(无论是通过模块内的代码还是通过引用模块的全局变量字典)不受影响。

Changed in version 3.5:版本3.5中更改: __class__ module attribute is now writable.模块属性现在可写。

New in version 3.7.版本3.7中新增。__getattr__ and __dir__ module attributes.模块属性。

See also参阅

PEP 562 - Module __getattr__ and __dir__

Describes the __getattr__ and __dir__ functions on modules.描述模块上的__getattr____dir__ 函数。

3.3.2.2. Implementing Descriptors实现描述符

The following methods only apply when an instance of the class containing the method (a so-called descriptor class) appears in an owner class (the descriptor must be in either the owner’s class dictionary or in the class dictionary for one of its parents). 以下方法仅在包含该方法的类的实例(所谓的descriptor类)出现在owner类中时适用(描述符必须位于所有者的类字典中,或位于其父类之一的类字典中)。In the examples below, “the attribute” refers to the attribute whose name is the key of the property in the owner class’ __dict__.在下面的示例中,“属性”指的是其名称是所有者类的__dict__中属性的键的属性。

object.__get__(self, instance, owner=None)

Called to get the attribute of the owner class (class attribute access) or of an instance of that class (instance attribute access). 调用以获取所有者类的属性(类属性访问)或该类的实例的属性(实例属性访问)。The optional owner argument is the owner class, while instance is the instance that the attribute was accessed through, or None when the attribute is accessed through the owner.可选的owner参数是owner类,而instance是通过其访问属性的实例,或者当通过owner访问属性时为None

This method should return the computed attribute value or raise an AttributeError exception.此方法应返回计算的属性值或引发AttributeError异常。

PEP 252 specifies that __get__() is callable with one or two arguments. 指定可使用一个或两个参数调用__get__()Python’s own built-in descriptors support this specification; however, it is likely that some third-party tools have descriptors that require both arguments. Python自己的内置描述符支持此规范;然而,一些第三方工具可能具有同时需要两个参数的描述符。Python’s own __getattribute__() implementation always passes in both arguments whether they are required or not.Python自己的__getattribute__()实现始终传入这两个参数,无论它们是否是必需的。

object.__set__(self, instance, value)

Called to set the attribute on an instance instance of the owner class to a new value, value.调用以将所有者类的实例instance上的属性设置为新值value

Note, adding __set__() or __delete__() changes the kind of descriptor to a “data descriptor”. 注意,添加__set__()__delete__()将描述符的类型改成了“数据描述符”。See Invoking Descriptors for more details.有关更多详细信息,请参阅调用描述符

object.__delete__(self, instance)

Called to delete the attribute on an instance instance of the owner class.调用以删除所有者类的实例instance上的属性。

The attribute __objclass__ is interpreted by the inspect module as specifying the class where this object was defined (setting this appropriately can assist in runtime introspection of dynamic class attributes). inspect模块将属性__objclass__解释为指定定义此对象的类(适当设置此属性有助于动态类属性的运行时自省)。For callables, it may indicate that an instance of the given type (or a subclass) is expected or required as the first positional argument (for example, CPython sets this attribute for unbound methods that are implemented in C).对于可调用项,它可能表示预期或需要给定类型(或子类)的实例作为第一个位置参数(例如,CPython为在C中实现的未绑定方法设置此属性)。

3.3.2.3. Invoking Descriptors调用描述符

In general, a descriptor is an object attribute with “binding behavior”, one whose attribute access has been overridden by methods in the descriptor protocol: __get__(), __set__(), and __delete__(). 通常,描述符是具有“绑定行为”的对象属性,其属性访问已被描述符协议中的方法覆盖:__get__()__set__()__delete__()If any of those methods are defined for an object, it is said to be a descriptor.如果这些方法中的任何一个是为对象定义的,则称之为描述符。

The default behavior for attribute access is to get, set, or delete the attribute from an object’s dictionary. 属性访问的默认行为是从对象的字典中获取、设置或删除属性。For instance, a.x has a lookup chain starting with a.__dict__['x'], then type(a).__dict__['x'], and continuing through the base classes of type(a) excluding metaclasses.例如,a.x有一个查找链,以a.__dict__['x']开始,然后是type(a).__dict__['x'],并继续遍历type(a)的基类,不包括元类。

However, if the looked-up value is an object defining one of the descriptor methods, then Python may override the default behavior and invoke the descriptor method instead. 但是,如果查找的值是定义其中一个描述符方法的对象,那么Python可能会覆盖默认行为并调用描述符方法。Where this occurs in the precedence chain depends on which descriptor methods were defined and how they were called.这种情况在优先链中发生的位置取决于定义了哪些描述符方法以及如何调用它们。

The starting point for descriptor invocation is a binding, a.x. 描述符调用的起点是绑定a.xHow the arguments are assembled depends on a:参数的组合方式取决于:

Direct Call直接调用

The simplest and least common call is when user code directly invokes a descriptor method: x.__get__(a).最简单也是最不常见的调用是当用户代码直接调用描述符方法时:x.__get__(a)

Instance Binding实例绑定

If binding to an object instance, a.x is transformed into the call: type(a).__dict__['x'].__get__(a, type(a)).如果绑定到对象实例,a.x将转换为调用:type(a).__dict__['x'].__get__(a, type(a))

Class Binding类绑定

If binding to a class, A.x is transformed into the call: A.__dict__['x'].__get__(None, A).如果绑定到类,A.x将转换为调用:A.__dict__['x'].__get__(None, A)

Super Binding超级绑定

If a is an instance of super, then the binding super(B, obj).m() searches obj.__class__.__mro__ for the base class A immediately following B and then invokes the descriptor with the call: A.__dict__['m'].__get__(obj, obj.__class__).如果asuper的实例,那么绑定super(B, obj).m()将搜索obj.__class__.__mro__,用于紧跟在B之后的基类A,然后通过调用A.__dict__['m'].__get__(obj, obj.__class__)调用描述符。

For instance bindings, the precedence of descriptor invocation depends on which descriptor methods are defined. 对于实例绑定,描述符调用的优先级取决于定义的描述符方法。A descriptor can define any combination of __get__(), __set__() and __delete__(). 描述符可以定义__get__()__set__()__delete__()If it does not define __get__(), then accessing the attribute will return the descriptor object itself unless there is a value in the object’s instance dictionary. 如果它没有定义__get__(),则访问该属性将返回描述符对象本身,除非该对象的实例字典中有值。If the descriptor defines __set__() and/or __delete__(), it is a data descriptor; if it defines neither, it is a non-data descriptor. 如果描述符定义了__set__()和/或__delete__(),则它是一个数据描述符;如果两者都没有定义,则它是非数据描述符。Normally, data descriptors define both __get__() and __set__(), while non-data descriptors have just the __get__() method. 通常,数据描述符同时定义__get__()__set__(),而非数据描述符只有__get__()方法。Data descriptors with __get__() and __set__() (and/or __delete__()) defined always override a redefinition in an instance dictionary. 定义了__get__()__set__()(和/或__delete__())的数据描述符始终覆盖实例字典中的重新定义。In contrast, non-data descriptors can be overridden by instances.相比之下,非数据描述符可以被实例覆盖。

Python methods (including those decorated with @staticmethod and @classmethod) are implemented as non-data descriptors. Python方法(包括那些用@staticmethod@classmethod修饰的方法)被实现为非数据描述符。Accordingly, instances can redefine and override methods. 因此,实例可以重新定义和重写方法。This allows individual instances to acquire behaviors that differ from other instances of the same class.这允许单个实例获取与同一类的其他实例不同的行为。

The property() function is implemented as a data descriptor. property()函数作为数据描述符实现。Accordingly, instances cannot override the behavior of a property.因此,实例不能重写属性的行为。

3.3.2.4. __slots__

__slots__ allow us to explicitly declare data members (like properties) and deny the creation of __dict__ and __weakref__ (unless explicitly declared in __slots__ or available in a parent.)__slots__允许我们显式声明数据成员(如属性)并拒绝创建__dict____weakref__(除非在__slots__中显式声明或在父级中可用。)

The space saved over using __dict__ can be significant. 使用__dict__节省的空间可能很大。Attribute lookup speed can be significantly improved as well.属性查找速度也可以显著提高。

object.__slots__

This class variable can be assigned a string, iterable, or sequence of strings with variable names used by instances. 可以为此类变量分配一个字符串、iterable或一系列字符串,这些字符串具有实例使用的变量名称。__slots__ reserves space for the declared variables and prevents the automatic creation of __dict__ and __weakref__ for each instance.__slots__为声明的变量保留空间,并防止为每个实例自动创建__dict____weakref__

3.3.2.4.1. Notes on using __slots__有关使用__slots__的说明__
  • When inheriting from a class without __slots__, the __dict__ and __weakref__ attribute of the instances will always be accessible.从没有__slots__的类继承时,实例的__dict____weakref__属性将始终可以访问。

  • Without a __dict__ variable, instances cannot be assigned new variables not listed in the __slots__ definition. 如果没有__dict__变量,则无法为实例分配__slots__定义中未列出的新变量。Attempts to assign to an unlisted variable name raises AttributeError. 尝试分配给未列出的变量名会引发AttributeErrorIf dynamic assignment of new variables is desired, then add '__dict__' to the sequence of strings in the __slots__ declaration.如果需要动态分配新变量,则将'__dict__'添加到__slots__声明中的字符串序列中。

  • Without a __weakref__ variable for each instance, classes defining __slots__ do not support weak references to its instances. 如果每个实例没有__weakref__变量,定义__slots__的类就不支持对其实例的弱引用If weak reference support is needed, then add '__weakref__' to the sequence of strings in the __slots__ declaration.如果需要弱引用支持,则需要把'__weakref__'添加到__slots__声明中的字符串序列。

  • __slots__ are implemented at the class level by creating descriptors for each variable name. __slots__通过为每个变量名创建描述符在类级别实现。As a result, class attributes cannot be used to set default values for instance variables defined by __slots__; otherwise, the class attribute would overwrite the descriptor assignment.因此,类属性不能用于设置由__slots__;否则,类属性将覆盖描述符分配。

  • The action of a __slots__ declaration is not limited to the class where it is defined. __slots__声明的操作不限于定义它的类。__slots__ declared in parents are available in child classes. 父类中声明的__slots__在子类中可用。However, child subclasses will get a __dict__ and __weakref__ unless they also define __slots__ (which should only contain names of any additional slots).但是,子类将获得一个__dict____weakref__,除非它们还定义了__slots__(它应该只包含任何其他插槽的名称)。

  • If a class defines a slot also defined in a base class, the instance variable defined by the base class slot is inaccessible (except by retrieving its descriptor directly from the base class). 如果一个类定义了一个同样在基类中定义的槽,则基类槽定义的实例变量是不可访问的(除非直接从基类检索其描述符)。This renders the meaning of the program undefined. 这使得程序的含义没有定义。In the future, a check may be added to prevent this.将来,可能会添加一个检查来防止出现这种情况。

  • Nonempty __slots__ does not work for classes derived from “variable-length” built-in types such as int, bytes and tuple.非空__slots__不适用于从“可变长度”内置类型(如intbytestuple)派生的类。

  • Any non-string iterable may be assigned to __slots__.任何非字符串iterable都可以分配给__slots__

  • If a dictionary is used to assign __slots__, the dictionary keys will be used as the slot names. 如果使用dictionary分配__slots__,则字典键将用作插槽名称。The values of the dictionary can be used to provide per-attribute docstrings that will be recognised by inspect.getdoc() and displayed in the output of help().字典的值可用于提供每个属性的docString,这些docString将由inspect.getdoc()识别并显示在help()的输出中。

  • __class__ assignment works only if both classes have the same __slots__.只有当两个类都有相同的__slots__时,__class__赋值才起作用。

  • Multiple inheritance with multiple slotted parent classes can be used, but only one parent is allowed to have attributes created by slots (the other bases must have empty slot layouts) - violations raise TypeError.可以使用具有多个时隙父类的多重继承,但只允许一个父类具有由时隙创建的属性(其他基必须具有空的时隙布局)-违反规则会引发TypeError

  • If an iterator is used for __slots__ then a descriptor is created for each of the iterator’s values. 如果迭代器用于__slots__,则会为迭代器的每个值创建一个描述符。However, the __slots__ attribute will be an empty iterator.但是,__slots__属性将是一个空迭代器。

3.3.3. Customizing class creation自定义类创建

Whenever a class inherits from another class, __init_subclass__() is called on the parent class. 每当一个类从另一个类继承时,都会对父类调用__init_subclass__()函数。This way, it is possible to write classes which change the behavior of subclasses. 这样,就可以编写更改子类行为的类。This is closely related to class decorators, but where class decorators only affect the specific class they’re applied to, __init_subclass__ solely applies to future subclasses of the class defining the method.这与类修饰符密切相关,但如果类修饰符只影响它们应用到的特定类,__init_subclass__仅适用于定义方法的类的未来子类。

classmethodobject.__init_subclass__(cls)

This method is called whenever the containing class is subclassed. 每当包含类被子类化时,就会调用此方法。cls is then the new subclass. cls是新的子类。If defined as a normal instance method, this method is implicitly converted to a class method.如果定义为普通实例方法,则此方法将隐式转换为类方法。

Keyword arguments which are given to a new class are passed to the parent’s class __init_subclass__. 给定给新类的关键字参数将传递给父类的类__init_subclass__For compatibility with other classes using __init_subclass__, one should take out the needed keyword arguments and pass the others over to the base class, as in:为了与使用__init_subclass__的其他类兼容,应该去掉所需的关键字参数,并将其他参数传递给基类,如下所示:

class Philosopher:
def __init_subclass__(cls, /, default_name, **kwargs):
super().__init_subclass__(**kwargs)
cls.default_name = default_name
class AustralianPhilosopher(Philosopher, default_name="Bruce"):
pass

The default implementation object.__init_subclass__ does nothing, but raises an error if it is called with any arguments.默认实现对象object.__init_subclass__不执行任何操作,但如果使用任何参数调用它,则会引发错误。

Note

The metaclass hint metaclass is consumed by the rest of the type machinery, and is never passed to __init_subclass__ implementations. 元类hintmetaclass由其余的类型机器使用,并且永远不会传递给__init_subclass__实现。The actual metaclass (rather than the explicit hint) can be accessed as type(cls).实际的元类(而不是显式提示)可以作为type(cls)访问。

New in version 3.6.版本3.6中新增。

When a class is created, type.__new__() scans the class variables and makes callbacks to those with a __set_name__() hook.创建类时,type.__new__()扫描类变量,并回调带有__set_name__()钩子的类变量。

object.__set_name__(self, owner, name)

Automatically called at the time the owning class owner is created. 在创建所属类owner时自动调用。The object has been assigned to name in that class:对象已分配给该类中的name

class A:
x = C() # Automatically calls: x.__set_name__(A, 'x')

If the class variable is assigned after the class is created, __set_name__() will not be called automatically. 如果在创建类之后分配了类变量,则不会自动调用__set_name__()If needed, __set_name__() can be called directly:如果需要,可以直接调用__set_name__()

class A:
pass
c = C()
A.x = c # The hook is not called
c.__set_name__(A, 'x') # Manually invoke the hook

See Creating the class object for more details.有关详细信息,请参阅创建类对象

New in version 3.6.版本3.6中新增。

3.3.3.1. Metaclasses元类

By default, classes are constructed using type(). 默认情况下,类是使用type()构造的。The class body is executed in a new namespace and the class name is bound locally to the result of type(name, bases, namespace).类主体在新名称空间中执行,类名在本地绑定到type(name, bases, namespace)的结果。

The class creation process can be customized by passing the metaclass keyword argument in the class definition line, or by inheriting from an existing class that included such an argument. 可以通过在类定义行中传递metaclass关键字参数,或者通过从包含此类参数的现有类继承来自定义类创建过程。In the following example, both MyClass and MySubclass are instances of Meta:在以下示例中,MyClassMySubclass都是Meta的实例:

class Meta(type):
pass
class MyClass(metaclass=Meta):
pass

class MySubclass(MyClass):
pass

Any other keyword arguments that are specified in the class definition are passed through to all metaclass operations described below.在类定义中指定的任何其他关键字参数都会传递给下面描述的所有元类操作。

When a class definition is executed, the following steps occur:执行类定义时,将执行以下步骤:

  • MRO entries are resolved;MRO条目已解决;

  • the appropriate metaclass is determined;确定适当的元类;

  • the class namespace is prepared;类名称空间已准备就绪;

  • the class body is executed;执行类主体;

  • the class object is created.将创建类对象。

3.3.3.2. Resolving MRO entries解析MRO条目

If a base that appears in class definition is not an instance of type, then an __mro_entries__ method is searched on it. 如果类定义中出现的基不是type的实例,则会在其上搜索__mro_entries__方法。If found, it is called with the original bases tuple. 如果找到,则使用原始的基元组调用它。This method must return a tuple of classes that will be used instead of this base. 此方法必须返回将要使用的类的元组,而不是此基。The tuple may be empty, in such case the original base is ignored.元组可能为空,在这种情况下,将忽略原始基。

See also参阅

PEP 560 - Core support for typing module and generic types对类型化模块和泛型类型的核心支持

3.3.3.3. Determining the appropriate metaclass确定适当的元类

The appropriate metaclass for a class definition is determined as follows:类定义的适当元类确定如下:

  • if no bases and no explicit metaclass are given, then type() is used;如果没有给出基和显式元类,则使用type()

  • if an explicit metaclass is given and it is not an instance of type(), then it is used directly as the metaclass;如果给出了一个显式元类,但它不是type()的实例,则直接将其用作元类;

  • if an instance of type() is given as the explicit metaclass, or bases are defined, then the most derived metaclass is used.如果将type()的实例作为显式元类给出,或定义了基,则使用派生最多的元类。

The most derived metaclass is selected from the explicitly specified metaclass (if any) and the metaclasses (i.e. type(cls)) of all specified base classes. 派生最多的元类是从显式指定的元类(如果有)和所有指定基类的元类(即type(cls))中选择的。The most derived metaclass is one which is a subtype of all of these candidate metaclasses. 派生最多的元类是所有这些候选元类的子类型。If none of the candidate metaclasses meets that criterion, then the class definition will fail with TypeError.如果没有一个候选元类满足该标准,那么类定义将失败,并出现TypeError

3.3.3.4. Preparing the class namespace准备类命名空间

Once the appropriate metaclass has been identified, then the class namespace is prepared. 一旦确定了适当的元类,就准备好了类名称空间。If the metaclass has a __prepare__ attribute, it is called as namespace = metaclass.__prepare__(name, bases, **kwds) (where the additional keyword arguments, if any, come from the class definition). 如果元类有一个__prepare__属性,则称之为namespace = metaclass.__prepare__(name, bases, **kwds)(其中额外的关键字参数(如果有的话)来自类定义)。The __prepare__ method should be implemented as a classmethod. __prepare__方法应作为classmethod实现。The namespace returned by __prepare__ is passed in to __new__, but when the final class object is created the namespace is copied into a new dict.__prepare__返回的命名空间传递给__new__,但是当创建最终的类对象时,命名空间被复制到新的dict中。

If the metaclass has no __prepare__ attribute, then the class namespace is initialised as an empty ordered mapping.如果元类没有__prepare__属性,则类命名空间将初始化为空的有序映射。

See also参阅

PEP 3115 - Metaclasses in Python 3000

Introduced the __prepare__ namespace hook引入了__prepare__命名空间挂钩

3.3.3.5. Executing the class body执行类主体

The class body is executed (approximately) as exec(body, globals(), namespace). 类主体作为exec(body, globals(), namespace)执行(大约)。The key difference from a normal call to exec() is that lexical scoping allows the class body (including any methods) to reference names from the current and outer scopes when the class definition occurs inside a function.与普通调用exec()的关键区别在于,当类定义出现在函数内部时,词法作用域允许类主体(包括任何方法)引用当前和外部作用域中的名称。

However, even when the class definition occurs inside the function, methods defined inside the class still cannot see names defined at the class scope. 然而,即使类定义发生在函数中,类中定义的方法仍然无法看到在类范围中定义的名称。Class variables must be accessed through the first parameter of instance or class methods, or through the implicit lexically scoped __class__ reference described in the next section.类变量必须通过实例或类方法的第一个参数访问,或者通过下一节中描述的隐式词汇范围的__class__引用访问。

3.3.3.6. Creating the class object创建类对象

Once the class namespace has been populated by executing the class body, the class object is created by calling metaclass(name, bases, namespace, **kwds) (the additional keywords passed here are the same as those passed to __prepare__).一旦通过执行类主体填充了类名称空间,就可以通过调用metaclass(name, bases, namespace, **kwds)来创建类对象(此处传递的其他关键字与传递给__prepare__的关键字相同)。

This class object is the one that will be referenced by the zero-argument form of super(). 该类对象将由super()的零参数形式引用。__class__ is an implicit closure reference created by the compiler if any methods in a class body refer to either __class__ or super. 如果类主体中的任何方法引用__class__super,则__class__是编译器创建的隐式闭包引用。This allows the zero argument form of super() to correctly identify the class being defined based on lexical scoping, while the class or instance that was used to make the current call is identified based on the first argument passed to the method.这允许super()的零参数形式正确标识基于词法作用域定义的类,而用于进行当前调用的类或实例则基于传递给该方法的第一个参数进行标识。

CPython implementation detail:CPython实施详情: In CPython 3.6 and later, the __class__ cell is passed to the metaclass as a __classcell__ entry in the class namespace. 在CPython 3.6及更高版本中,__class__单元格作为类命名空间中的__classcell__条目传递给元类。If present, this must be propagated up to the type.__new__ call in order for the class to be initialised correctly. 如果存在,则必须将其传播到类型type.__new__调用以正确初始化类。Failing to do so will result in a RuntimeError in Python 3.8.否则将导致Python 3.8中出现RuntimeError

When using the default metaclass type, or any metaclass that ultimately calls type.__new__, the following additional customization steps are invoked after creating the class object:使用默认元类type.__new__或最终调用type的任何元类时,创建类对象后将调用以下其他自定义步骤:

  1. The type.__new__ method collects all of the attributes in the class namespace that define a __set_name__() method;type.__new__收集类命名空间中定义__set_name__()方法的所有属性;

  2. Those __set_name__ methods are called with the class being defined and the assigned name of that particular attribute;调用这些__set_name__方法时,将定义类并指定该特定属性的名称;

  3. The __init_subclass__() hook is called on the immediate parent of the new class in its method resolution order.在新类的直接父级上按其方法解析顺序调用__init_subclass__()钩子。

After the class object is created, it is passed to the class decorators included in the class definition (if any) and the resulting object is bound in the local namespace as the defined class.创建类对象后,将其传递给类定义中包含的类装饰器(如果有),并将生成的对象作为定义的类绑定到本地命名空间中。

When a new class is created by type.__new__, the object provided as the namespace parameter is copied to a new ordered mapping and the original object is discarded. type.__new__创建新类时,作为命名空间参数提供的对象将复制到新的有序映射,并丢弃原始对象。The new copy is wrapped in a read-only proxy, which becomes the __dict__ attribute of the class object.新副本包装在只读代理中,该代理将成为类对象的__dict__属性。

See also参阅

PEP 3135 - New super

Describes the implicit __class__ closure reference描述隐式__class__闭包引用

3.3.3.7. Uses for metaclasses元类的用法

The potential uses for metaclasses are boundless. 元类的潜在用途是无限的。Some ideas that have been explored include enum, logging, interface checking, automatic delegation, automatic property creation, proxies, frameworks, and automatic resource locking/synchronization.已经探讨过的一些想法包括枚举、日志记录、接口检查、自动委派、自动属性创建、代理、框架和自动资源锁定/同步。

3.3.4. Customizing instance and subclass checks自定义实例和子类检查

The following methods are used to override the default behavior of the isinstance() and issubclass() built-in functions.以下方法用于重写isinstance()issubclass()内置函数的默认行为。

In particular, the metaclass abc.ABCMeta implements these methods in order to allow the addition of Abstract Base Classes (ABCs) as “virtual base classes” to any class or type (including built-in types), including other ABCs.特别是,元类abc.ABCMeta实现这些方法,以便允许将抽象基类(ABC)作为“虚拟基类”添加到任何类或类型(包括内置类型),包括其他ABC。

class.__instancecheck__(self, instance)

Return true if instance should be considered a (direct or indirect) instance of class. 如果instance应被视为class的(直接或间接)实例,则返回trueIf defined, called to implement isinstance(instance, class).如果已定义,则调用以实现isinstance(instance, class)

class.__subclasscheck__(self, subclass)

Return true if subclass should be considered a (direct or indirect) subclass of class. 如果subclass应被视为class的(直接或间接)子类,则返回trueIf defined, called to implement issubclass(subclass, class).如果已定义,则调用以实现issubclass(subclass, class)

Note that these methods are looked up on the type (metaclass) of a class. 请注意,这些方法是在类的类型(元类)上查找的。They cannot be defined as class methods in the actual class. 它们不能定义为实际类中的类方法。This is consistent with the lookup of special methods that are called on instances, only in this case the instance is itself a class.这与在实例上调用的特殊方法的查找是一致的,只有在这种情况下,实例本身是一个类。

See also参阅

PEP 3119 - Introducing Abstract Base Classes引入抽象基类

Includes the specification for customizing isinstance() and issubclass() behavior through __instancecheck__() and __subclasscheck__(), with motivation for this functionality in the context of adding Abstract Base Classes (see the abc module) to the language.包括通过isinstance()__subclasscheck__()自定义isinstance()issubclass()行为的规范,并在向语言添加抽象基类(请参阅abc模块)的上下文中激励此功能。

3.3.5. Emulating generic types模拟泛型类型

When using type annotations, it is often useful to parameterize a generic type using Python’s square-brackets notation. 使用类型注释时,使用Python的方括号表示法参数化泛型类型通常很有用。For example, the annotation list[int] might be used to signify a list in which all the elements are of type int.例如,注释list[int]可以用来表示一个list,其中所有元素的类型都是int

See also参阅

PEP 484 - Type Hints键入提示

Introducing Python’s framework for type annotations介绍Python的类型注释框架

Generic Alias Types泛型别名类型

Documentation for objects representing parameterized generic classes表示参数化泛型类的对象的文档

Generics, user-defined generics and typing.Generic泛型用户定义的泛型typing.Generic

Documentation on how to implement generic classes that can be parameterized at runtime and understood by static type-checkers.关于如何实现泛型类的文档,这些泛型类可以在运行时参数化,并且可以被静态类型检查器理解。

A class can generally only be parameterized if it defines the special class method __class_getitem__().通常,仅当类定义了特殊的类方法__class_getitem__()时,才能对其进行参数化。

classmethodobject.__class_getitem__(cls, key)

Return an object representing the specialization of a generic class by type arguments found in key.返回一个对象,该对象通过中的类型参数表示泛型类的专门化。

When defined on a class, __class_getitem__() is automatically a class method. 在类上定义时,__class_getitem__()自动成为类方法。As such, there is no need for it to be decorated with @classmethod when it is defined.因此,无需使用@classmethod

3.3.5.1. The purpose of __class_getitem____class_getitem__的目的

The purpose of __class_getitem__() is to allow runtime parameterization of standard-library generic classes in order to more easily apply type hints to these classes.__class_getitem__()的目的是允许标准库泛型类的运行时参数化,以便更轻松地将类型提示应用于这些类。

To implement custom generic classes that can be parameterized at runtime and understood by static type-checkers, users should either inherit from a standard library class that already implements __class_getitem__(), or inherit from typing.Generic, which has its own implementation of __class_getitem__().要实现可在运行时参数化并可被静态类型检查器理解的自定义泛型类,用户应该继承已经实现了__class_getitem__()的标准库类,或者继承typing.Generic,后者有自己的__class_getitem__()实现。

Custom implementations of __class_getitem__() on classes defined outside of the standard library may not be understood by third-party type-checkers such as mypy. 第三方类型检查器(如mypy)可能无法理解在标准库之外定义的类上的__class_getitem__()的自定义实现。Using __class_getitem__() on any class for purposes other than type hinting is discouraged.不鼓励在任何类上使用__class_getitem__()用于类型暗示以外的目的。

3.3.5.2. __class_getitem__ versus 对比__getitem__

Usually, the subscription of an object using square brackets will call the __getitem__() instance method defined on the object’s class. 通常,使用方括号订阅对象将调用在对象类上定义的__getitem__()实例方法。However, if the object being subscribed is itself a class, the class method __class_getitem__() may be called instead. 但是,如果订阅的对象本身是一个类,则可以调用类方法__class_getitem__()__class_getitem__() should return a GenericAlias object if it is properly defined.如果正确定义了GenericAlias对象,则应返回该对象。

Presented with the expression obj[x], the Python interpreter follows something like the following process to decide whether __getitem__() or __class_getitem__() should be called:Python解释器使用表达式obj[x]执行类似以下过程的操作,以决定是调用__getitem__()还是调用__class_getitem__()

from inspect import isclass
def subscribe(obj, x):
"""Return the result of the expression `obj[x]`"""

class_of_obj = type(obj)

# If the class of obj defines __getitem__,
# call class_of_obj.__getitem__(obj, x)
if hasattr(class_of_obj, '__getitem__'):
return class_of_obj.__getitem__(obj, x)

# Else, if obj is a class and defines __class_getitem__,
# call obj.__class_getitem__(x)
elif isclass(obj) and hasattr(obj, '__class_getitem__'):
return obj.__class_getitem__(x)

# Else, raise an exception
else:
raise TypeError(
f"'{class_of_obj.__name__}' object is not subscriptable"
)

In Python, all classes are themselves instances of other classes. 在Python中,所有类本身都是其他类的实例。The class of a class is known as that class’s metaclass, and most classes have the type class as their metaclass. 一个类的类称为该类的元类,大多数类的元类都是type类。type does not define __getitem__(), meaning that expressions such as list[int], dict[str, float] and tuple[str, bytes] all result in __class_getitem__() being called:type未定义__getitem__(),这意味着诸如list[int]dict[str, float]tuple[str, bytes]之类的表达式都会导致调用__class_getitem__()

>>> # list has class "type" as its metaclass, like most classes:
>>> type(list)
<class 'type'>
>>> type(dict) == type(list) == type(tuple) == type(str) == type(bytes)
True
>>> # "list[int]" calls "list.__class_getitem__(int)"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type(list[int])
<class 'types.GenericAlias'>

However, if a class has a custom metaclass that defines __getitem__(), subscribing the class may result in different behaviour. 但是,如果一个类有一个定义了__getitem__()的自定义元类,订阅该类可能会导致不同的行为。An example of this can be found in the enum module:这方面的一个示例可以在enum模块中找到:

>>> from enum import Enum
>>> class Menu(Enum):
... """A breakfast menu"""
... SPAM = 'spam'
... BACON = 'bacon'
...
>>> # Enum classes have a custom metaclass:
>>> type(Menu)
<class 'enum.EnumMeta'>
>>> # EnumMeta defines __getitem__,
>>> # so __class_getitem__ is not called,
>>> # and the result is not a GenericAlias object:
>>> Menu['SPAM']
<Menu.SPAM: 'spam'>
>>> type(Menu['SPAM'])
<enum 'Menu'>

See also参阅

PEP 560 - Core Support for typing module and generic types对类型化模块和泛型类型的核心支持

Introducing __class_getitem__(), and outlining when a subscription results in __class_getitem__() being called instead of __getitem__()介绍__class_getitem__(),并概述订阅何时导致调用__class_getitem__()而不是__getitem__()

3.3.6. Emulating callable objects模拟可调用对象

object.__call__(self[, args...])

Called when the instance is “called” as a function; if this method is defined, x(arg1, arg2, ...) roughly translates to type(x).__call__(x, arg1, ...).当实例作为函数“调用”时调用;如果定义了此方法,则x(arg1, arg2, ...)大致转换为type(x).__call__(x, arg1, ...)

3.3.7. Emulating container types模拟容器类型

The following methods can be defined to implement container objects. 可以定义以下方法来实现容器对象。Containers usually are sequences (such as lists or tuples) or mappings (like dictionaries), but can represent other containers as well. 容器通常是序列(如liststuples)或映射(如dictionaries),但也可以表示其他容器。The first set of methods is used either to emulate a sequence or to emulate a mapping; the difference is that for a sequence, the allowable keys should be the integers k for which 0 <= k < N where N is the length of the sequence, or slice objects, which define a range of items. 第一组方法用于模拟序列或模拟映射;不同之处在于,对于序列,允许的键应该是整数k,其中0 <= k < N,其中N是序列的长度,或者是定义项目范围的切片对象。It is also recommended that mappings provide the methods keys(), values(), items(), get(), clear(), setdefault(), pop(), popitem(), copy(), and update() behaving similar to those for Python’s standard dictionary objects. 还建议映射提供方法keys()values()items()get()clear()setdefault()pop()popitem()copy()update(),其行为类似于Python的标准字典对象。The collections.abc module provides a MutableMapping abstract base class to help create those methods from a base set of __getitem__(), __setitem__(), __delitem__(), and keys(). collections.abc模块提供了一个MutableMapping抽象基类,以帮助从__getitem__()__delitem__()__delitem__()keys()的基集创建这些方法。Mutable sequences should provide methods append(), count(), index(), extend(), insert(), pop(), remove(), reverse() and sort(), like Python standard list objects. 可变序列应该提供方法append()count()index()extend()insert()pop()remove()reverse()sort(),就像Python标准的list对象一样。Finally, sequence types should implement addition (meaning concatenation) and multiplication (meaning repetition) by defining the methods __add__(), __radd__(), __iadd__(), __mul__(), __rmul__() and __imul__() described below; they should not define other numerical operators. 最后,序列类型应该通过定义下面描述的方法__add__()__radd__()__iadd__()__mul__()__rmul__()__imul__()来实现加法(意味着串联)和乘法(意味着重复);它们不应定义其他数值运算符。It is recommended that both mappings and sequences implement the __contains__() method to allow efficient use of the in operator; for mappings, in should search the mapping’s keys; for sequences, it should search through the values. 建议映射和序列都实现__contains__()方法,以允许有效使用in运算符;对于映射,in应搜索映射的键;对于序列,它应该搜索值。It is further recommended that both mappings and sequences implement the __iter__() method to allow efficient iteration through the container; for mappings, __iter__() should iterate through the object’s keys; for sequences, it should iterate through the values.进一步建议映射和序列都实现__iter__()方法,以允许通过容器进行有效迭代;对于映射,__iter__()应该遍历对象的键;对于序列,它应该遍历这些值。

object.__len__(self)

Called to implement the built-in function len(). 调用以实现内置函数len()Should return the length of the object, an integer >= 0. 应返回对象的长度,整数>=0Also, an object that doesn’t define a __bool__() method and whose __len__() method returns zero is considered to be false in a Boolean context.此外,在布尔上下文中,如果一个对象没有定义__bool__()方法并且其__len__()方法返回零,则该对象被视为false

CPython implementation detail:CPython实施详情: In CPython, the length is required to be at most sys.maxsize. 在CPython中,长度要求最大为sys.maxsizeIf the length is larger than sys.maxsize some features (such as len()) may raise OverflowError. 如果长度大于sys.maxsize,则某些功能(如len())可能会引发溢出错误。To prevent raising OverflowError by truth value testing, an object must define a __bool__() method.为了防止通过真值测试引发OverflowError,对象必须定义一个__bool__()方法。

object.__length_hint__(self)

Called to implement operator.length_hint(). 调用以实现operator.length_hint()Should return an estimated length for the object (which may be greater or less than the actual length). 应返回对象的估计长度(可能大于或小于实际长度)。The length must be an integer >= 0. 长度必须是大于等于0的整数。The return value may also be NotImplemented, which is treated the same as if the __length_hint__ method didn’t exist at all. 返回值也可能是NotImplemented,这与__length_hint__方法根本不存在一样。This method is purely an optimization and is never required for correctness.这种方法纯粹是一种优化,不需要正确性。

New in version 3.4.版本3.4中新增。

Note

Slicing is done exclusively with the following three methods. 切片只使用以下三种方法完成。A call like

a[1:2] = b

is translated to

a[slice(1, 2, None)] = b

and so forth. 等等Missing slice items are always filled in with None.缺少的切片项目总是用None填充。

object.__getitem__(self, key)

Called to implement evaluation of self[key]. 调用以执行self[key]评估。For sequence types, the accepted keys should be integers and slice objects. 对于序列类型,接受的键应该是整数和切片对象。Note that the special interpretation of negative indexes (if the class wishes to emulate a sequence type) is up to the __getitem__() method. 请注意,负索引的特殊解释(如果类希望模拟序列类型)取决于__getitem__()方法。If key is of an inappropriate type, TypeError may be raised; if of a value outside the set of indexes for the sequence (after any special interpretation of negative values), IndexError should be raised. 如果key的类型不合适,可能会引发TypeError;如果某个值超出了序列的索引集(在对负值进行任何特殊解释之后),则应引发IndexErrorFor mapping types, if key is missing (not in the container), KeyError should be raised.对于映射类型,如果缺少key(不在容器中),则应引发KeyError

Note

for loops expect that an IndexError will be raised for illegal indexes to allow proper detection of the end of the sequence.循环期望针对非法索引引发IndexError,以允许正确检测序列的结尾。

Note

When subscripting a class, the special class method __class_getitem__() may be called instead of __getitem__(). 订阅class时,可以调用特殊的类方法__class_getitem__(),而不是__getitem__()See __class_getitem__ versus __getitem__ for more details.有关更多详细信息,请参阅__class_getitem____getitem__的比较

object.__setitem__(self, key, value)

Called to implement assignment to self[key]. 调用以实现对self[key]的分配。Same note as for __getitem__(). 注释与__getitem__()相同。This should only be implemented for mappings if the objects support changes to the values for keys, or if new keys can be added, or for sequences if elements can be replaced. 只有当对象支持更改键的值时,或者如果可以添加新键,或者如果可以替换元素,才应该为映射实现这一点。The same exceptions should be raised for improper key values as for the __getitem__() method.对于不正确的key值,应引发与__getitem__()方法相同的异常。

object.__delitem__(self, key)

Called to implement deletion of self[key]. 调用以实现删除self[key]Same note as for __getitem__(). 注释与__getitem__()相同。This should only be implemented for mappings if the objects support removal of keys, or for sequences if elements can be removed from the sequence. 仅当对象支持删除键时,才应为映射实现此功能;如果可以从序列中删除元素,则应为序列实现此功能。The same exceptions should be raised for improper key values as for the __getitem__() method.对于不正确的key值,应引发与__getitem__()方法相同的异常。

object.__missing__(self, key)

Called by dict.__getitem__() to implement self[key] for dict subclasses when key is not in the dictionary.dict.__getitem__()调用,以在dict子类的键不在字典中时实现self[key]

object.__iter__(self)

This method is called when an iterator is required for a container. 当容器需要迭代器时,调用此方法。This method should return a new iterator object that can iterate over all the objects in the container. 此方法应返回一个新的迭代器对象,该对象可以迭代容器中的所有对象。For mappings, it should iterate over the keys of the container.对于映射,它应该迭代容器的键。

object.__reversed__(self)

Called (if present) by the reversed() built-in to implement reverse iteration. 由内置的reversed()调用(如果存在)以实现反向迭代。It should return a new iterator object that iterates over all the objects in the container in reverse order.它应该返回一个新的迭代器对象,该对象按相反顺序遍历容器中的所有对象。

If the __reversed__() method is not provided, the reversed() built-in will fall back to using the sequence protocol (__len__() and __getitem__()). 如果没有提供__reversed__()方法,则reversed()内置程序将退回到使用序列协议(__len__()__getitem__()的状态)。Objects that support the sequence protocol should only provide __reversed__() if they can provide an implementation that is more efficient than the one provided by reversed().如果支持序列协议的对象可以提供比reversed()提供的实现更高效的实现,则它们只应提供__reversed__()

The membership test operators (in and not in) are normally implemented as an iteration through a container. 成员资格测试运算符(innot in)通常作为通过容器的迭代来实现。However, container objects can supply the following special method with a more efficient implementation, which also does not require the object be iterable.然而,容器对象可以为以下特殊方法提供更高效的实现,这也不要求对象是可移植的。

object.__contains__(self, item)

Called to implement membership test operators. 调用以实现成员身份测试运算符。Should return true if item is in self, false otherwise. 如果项位于self中,则应返回true,否则返回falseFor mapping objects, this should consider the keys of the mapping rather than the values or the key-item pairs.对于映射对象,这应该考虑映射的键,而不是值或键项对。

For objects that don’t define __contains__(), the membership test first tries iteration via __iter__(), then the old sequence iteration protocol via __getitem__(), see this section in the language reference.对于未定义__contains__()的对象,成员身份测试首先尝试通过__iter__()进行迭代,然后通过__getitem__()尝试旧的序列迭代协议,请参阅语言参考中的this部分。

3.3.8. Emulating numeric types模拟数字类型

The following methods can be defined to emulate numeric objects. 可以定义以下方法来模拟数值对象。Methods corresponding to operations that are not supported by the particular kind of number implemented (e.g., bitwise operations for non-integral numbers) should be left undefined.与实现的特定类型的数字不支持的操作相对应的方法(例如,非整数的位操作)应保持未定义。

object.__add__(self, other)
object.__sub__(self, other)
object.__mul__(self, other)
object.__matmul__(self, other)
object.__truediv__(self, other)
object.__floordiv__(self, other)
object.__mod__(self, other)
object.__divmod__(self, other)
object.__pow__(self, other[, modulo])
object.__lshift__(self, other)
object.__rshift__(self, other)
object.__and__(self, other)
object.__xor__(self, other)
object.__or__(self, other)

These methods are called to implement the binary arithmetic operations (+, -, *, @, /, //, %, divmod(), pow(), **, <<, >>, &, ^, |). 调用这些方法来实现二进制算术运算(+-*@///%divmod()pow()**<<>>^|)。For instance, to evaluate the expression x + y, where x is an instance of a class that has an __add__() method, x.__add__(y) is called. 例如,要计算表达式x + y,其中x是具有__add__()方法的类的实例,将调用x.__add__(y)The __divmod__() method should be the equivalent to using __floordiv__() and __mod__(); it should not be related to __truediv__(). __divmod__()方法应等同于使用__floordiv__()__mod__();它不应与__truediv__()相关。Note that __pow__() should be defined to accept an optional third argument if the ternary version of the built-in pow() function is to be supported.请注意,如果要支持内置pow()函数的三元版本,则应将__pow__()定义为接受可选的第三个参数。

If one of those methods does not support the operation with the supplied arguments, it should return NotImplemented.如果其中一个方法不支持带有所提供参数的操作,则应返回NotImplemented

object.__radd__(self, other)
object.__rsub__(self, other)
object.__rmul__(self, other)
object.__rmatmul__(self, other)
object.__rtruediv__(self, other)
object.__rfloordiv__(self, other)
object.__rmod__(self, other)
object.__rdivmod__(self, other)
object.__rpow__(self, other[, modulo])
object.__rlshift__(self, other)
object.__rrshift__(self, other)
object.__rand__(self, other)
object.__rxor__(self, other)
object.__ror__(self, other)

These methods are called to implement the binary arithmetic operations (+, -, *, @, /, //, %, divmod(), pow(), **, <<, >>, &, ^, |) with reflected (swapped) operands. 调用这些方法可使用反射(交换)操作数实现二进制算术运算(+-*@///%divmod()pow()**<<>>^|)。These functions are only called if the left operand does not support the corresponding operation 3 and the operands are of different types. 仅当左操作数不支持相应的运算3且操作数类型不同时,才调用这些函数。4 For instance, to evaluate the expression x - y, where y is an instance of a class that has an __rsub__() method, y.__rsub__(x) is called if x.__sub__(y) returns NotImplemented.例如,要计算表达式x - y,其中y是具有__rsub__()方法的类的实例,如果x.__sub__(y)返回NotImplemented,则调用y.__rsub__(x)

Note that ternary pow() will not try calling __rpow__() (the coercion rules would become too complicated).请注意,三元pow()不会尝试调用__rpow__()

Note

If the right operand’s type is a subclass of the left operand’s type and that subclass provides a different implementation of the reflected method for the operation, this method will be called before the left operand’s non-reflected method. 如果右操作数的类型是左操作数类型的子类,并且该子类为运算提供了反射方法的不同实现,则将在左操作数的非反射方法之前调用此方法。This behavior allows subclasses to override their ancestors’ operations.此行为允许子类重写其祖先的操作。

object.__iadd__(self, other)
object.__isub__(self, other)
object.__imul__(self, other)
object.__imatmul__(self, other)
object.__itruediv__(self, other)
object.__ifloordiv__(self, other)
object.__imod__(self, other)
object.__ipow__(self, other[, modulo])
object.__ilshift__(self, other)
object.__irshift__(self, other)
object.__iand__(self, other)
object.__ixor__(self, other)
object.__ior__(self, other)

These methods are called to implement the augmented arithmetic assignments (+=, -=, *=, @=, /=, //=, %=, **=, <<=, >>=, &=, ^=, |=). 调用这些方法来实现增广算术赋值(+=-=*=@=/=//=%=**=<<=>>=&=^=|=)。These methods should attempt to do the operation in-place (modifying self) and return the result (which could be, but does not have to be, self). 这些方法应该尝试就地执行操作(修改self)并返回结果(可能是,但不一定是self)。If a specific method is not defined, the augmented assignment falls back to the normal methods. 如果未定义特定方法,则增广赋值将返回到常规方法。For instance, if x is an instance of a class with an __iadd__() method, x += y is equivalent to x = x.__iadd__(y) . 例如,如果x是具有__iadd__()方法的类的实例,则x += y相当于x = x.__iadd__(y)Otherwise, x.__add__(y) and y.__radd__(x) are considered, as with the evaluation of x + y. 否则,将考虑x.__add__(y)y.__radd__(x),与x + y的计算一样。In certain situations, augmented assignment can result in unexpected errors (see Why does a_tuple[i] += [‘item’] raise an exception when the addition works?), but this behavior is in fact part of the data model.在某些情况下,扩充赋值可能会导致意外错误(请参见为什么在加法有效时,_tuple[i]+=['item']会引发异常?),但这种行为实际上是数据模型的一部分。

object.__neg__(self)
object.__pos__(self)
object.__abs__(self)
object.__invert__(self)

Called to implement the unary arithmetic operations (-, +, abs() and ~).调用以实现一元算术运算(-+abs()~)。

object.__complex__(self)
object.__int__(self)
object.__float__(self)

Called to implement the built-in functions complex(), int() and float(). 调用以实现内置函数complex()int()float()Should return a value of the appropriate type.应返回适当类型的值。

object.__index__(self)

Called to implement operator.index(), and whenever Python needs to losslessly convert the numeric object to an integer object (such as in slicing, or in the built-in bin(), hex() and oct() functions). 调用以实现operator.index(),并且每当Python需要无损地将数值对象转换为整数对象时(例如在切片中,或在内置的bin()hex()oct()函数中)。Presence of this method indicates that the numeric object is an integer type. 此方法表示数值对象是整数类型。Must return an integer.必须返回整数。

If __int__(), __float__() and __complex__() are not defined then corresponding built-in functions int(), float() and complex() fall back to __index__().如果未定义__int__()__float__()__complex__(),则相应的内置函数int()float()complex()返回到__index__()

object.__round__(self[, ndigits])
object.__trunc__(self)
object.__floor__(self)
object.__ceil__(self)

Called to implement the built-in function round() and math functions trunc(), floor() and ceil(). 调用以实现内置函数round()数学函数trunc()floor()ceil()Unless ndigits is passed to __round__() all these methods should return the value of the object truncated to an Integral (typically an int).除非将ndigits传递给__round__(),否则所有这些方法都应返回被截断为整数(通常为int)的对象的值。

The built-in function int() falls back to __trunc__() if neither __int__() nor __index__() is defined.如果既没有定义__int__()也没有定义__index__(),则内置函数int()将返回到__trunc__()

3.3.9. With Statement Context Managers使用语句上下文管理器

A context manager is an object that defines the runtime context to be established when executing a with statement. 上下文管理器是一个对象,它定义了在执行with语句时要建立的运行时上下文。The context manager handles the entry into, and the exit from, the desired runtime context for the execution of the block of code. 上下文管理器处理执行代码块所需的运行时上下文的入口和出口。Context managers are normally invoked using the with statement (described in section The with statement), but can also be used by directly invoking their methods.上下文管理器通常使用with语句调用(在with语句一节中描述),但也可以通过直接调用其方法来使用。

Typical uses of context managers include saving and restoring various kinds of global state, locking and unlocking resources, closing opened files, etc.上下文管理器的典型用途包括保存和恢复各种全局状态、锁定和解锁资源、关闭打开的文件等。

For more information on context managers, see Context Manager Types.有关上下文管理器的详细信息,请参阅上下文管理器类型

object.__enter__(self)

Enter the runtime context related to this object. 输入与此对象相关的运行时上下文。The with statement will bind this method’s return value to the target(s) specified in the as clause of the statement, if any.with语句将此方法的返回值绑定到语句的as子句中指定的目标(如果有)。

object.__exit__(self, exc_type, exc_value, traceback)

Exit the runtime context related to this object. 退出与此对象相关的运行时上下文。The parameters describe the exception that caused the context to be exited. 这些参数描述导致上下文退出的异常。If the context was exited without an exception, all three arguments will be None.如果上下文无异常退出,则所有三个参数都将为None

If an exception is supplied, and the method wishes to suppress the exception (i.e., prevent it from being propagated), it should return a true value. 如果提供了一个异常,并且该方法希望抑制该异常(即防止其传播),那么它应该返回一个真值。Otherwise, the exception will be processed normally upon exit from this method.否则,退出此方法时将正常处理异常。

Note that __exit__() methods should not reraise the passed-in exception; this is the caller’s responsibility.请注意,__exit__()方法不应重新释放传入的异常;这是调用方的责任。

See also参阅

PEP 343 - The “with” statement“with”语句

The specification, background, and examples for the Python with statement.Python with语句的规范、背景和示例。

3.3.10. Customizing positional arguments in class pattern matching自定义类模式匹配中的位置参数

When using a class name in a pattern, positional arguments in the pattern are not allowed by default, i.e. case MyClass(x, y) is typically invalid without special support in MyClass. 在模式中使用类名时,默认情况下不允许在模式中使用位置参数,即case MyClass(x, y)MyClass中没有特殊支持时通常无效。To be able to use that kind of patterns, the class needs to define a __match_args__ attribute.为了能够使用这种模式,类需要定义一个__match_args__属性。

object.__match_args__

This class variable can be assigned a tuple of strings. 可以为该类变量分配一个字符串元组。When this class is used in a class pattern with positional arguments, each positional argument will be converted into a keyword argument, using the corresponding value in __match_args__ as the keyword. 当在具有位置参数的类模式中使用此类时,每个位置参数都将转换为关键字参数,并使用__match_args__中的相应值作为关键字。The absence of this attribute is equivalent to setting it to ().缺少此属性相当于将其设置为()

For example, if MyClass.__match_args__ is ("left", "center", "right") that means that case MyClass(x, y) is equivalent to case MyClass(left=x, center=y). 例如,如果MyClass.__match_args__("left", "center", "right"),这意味着case MyClass(x, y)case MyClass(left=x, center=y)等效。Note that the number of arguments in the pattern must be smaller than or equal to the number of elements in __match_args__; if it is larger, the pattern match attempt will raise a TypeError.请注意,模式中的参数数量必须小于或等于__match_args__;如果较大,则模式匹配尝试将引发TypeError

New in version 3.10.版本3.10中新增。

See also参阅

PEP 634 - Structural Pattern Matching结构模式匹配

The specification for the Python match statement.Python match语句的规范。

3.3.11. Special method lookup特殊方法查找

For custom classes, implicit invocations of special methods are only guaranteed to work correctly if defined on an object’s type, not in the object’s instance dictionary. 对于自定义类,只有在对象的类型上定义,而不是在对象的实例字典中定义时,才能保证特殊方法的隐式调用正常工作。That behaviour is the reason why the following code raises an exception:这种行为是以下代码引发异常的原因:

>>> class C:
... pass
...
>>> c = C()
>>> c.__len__ = lambda: 5
>>> len(c)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: object of type 'C' has no len()

The rationale behind this behaviour lies with a number of special methods such as __hash__() and __repr__() that are implemented by all objects, including type objects. If the implicit lookup of these methods used the conventional lookup process, they would fail when invoked on the type object itself:这种行为背后的基本原理在于许多特殊方法,例如由所有对象(包括类型对象)实现的__hash__()方法和__repr__()方法。如果这些方法的隐式查找使用传统的查找过程,则在类型对象本身上调用时,它们将失败:

>>> 1 .__hash__() == hash(1)
True
>>> int.__hash__() == hash(int)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: descriptor '__hash__' of 'int' object needs an argument

Incorrectly attempting to invoke an unbound method of a class in this way is sometimes referred to as ‘metaclass confusion’, and is avoided by bypassing the instance when looking up special methods:以这种方式错误地调用类的未绑定方法有时被称为“元类混淆”,在查找特殊方法时,可以通过绕过实例来避免:

>>> type(1).__hash__(1) == hash(1)
True
>>> type(int).__hash__(int) == hash(int)
True

In addition to bypassing any instance attributes in the interest of correctness, implicit special method lookup generally also bypasses the __getattribute__() method even of the object’s metaclass:除了为了正确性而绕过任何实例属性外,隐式特殊方法查找通常也会绕过对象元类的__getattribute__()方法:

>>> class Meta(type):
... def __getattribute__(*args):
... print("Metaclass getattribute invoked")
... return type.__getattribute__(*args)
...
>>> class C(object, metaclass=Meta):
... def __len__(self):
... return 10
... def __getattribute__(*args):
... print("Class getattribute invoked")
... return object.__getattribute__(*args)
...
>>> c = C()
>>> c.__len__() # Explicit lookup via instance
Class getattribute invoked
10
>>> type(c).__len__(c) # Explicit lookup via type
Metaclass getattribute invoked
10
>>> len(c) # Implicit lookup
10

Bypassing the __getattribute__() machinery in this fashion provides significant scope for speed optimisations within the interpreter, at the cost of some flexibility in the handling of special methods (the special method must be set on the class object itself in order to be consistently invoked by the interpreter).以这种方式绕过__getattribute__()机制为解释器内的速度优化提供了很大的空间,但代价是在处理特殊方法时有一定的灵活性(必须在类对象本身上设置特殊方法,以便解释器一致地调用)。

3.4. Coroutines协同程序

3.4.1. Awaitable Objects可等待的对象

An awaitable object generally implements an __await__() method. awaitable对象通常实现一个__await__()方法。Coroutine objects returned from async def functions are awaitable.async def函数返回的协同路由对象是可等待的对象。

Note

The generator iterator objects returned from generators decorated with types.coroutine() or asyncio.coroutine() are also awaitable, but they do not implement __await__().从用types.coroutine()asyncio.coroutine()修饰的生成器返回的生成器迭代器对象也是可以等待的,但它们没有实现__await__()

object.__await__(self)

Must return an iterator. 必须返回迭代器Should be used to implement awaitable objects. 应用于实现可等待的对象。For instance, asyncio.Future implements this method to be compatible with the await expression.例如,asyncio.Future实现此方法以与await表达式兼容。

New in version 3.5.版本3.5中新增。

See also参阅

PEP 492 for additional information about awaitable objects.有关等待对象的其他信息。

3.4.2. Coroutine Objects协同路由对象

Coroutine objects are awaitable objects. 协同路由对象可等待的对象。A coroutine’s execution can be controlled by calling __await__() and iterating over the result. 可以通过调用__await__()并迭代结果来控制协同路由的执行。When the coroutine has finished executing and returns, the iterator raises StopIteration, and the exception’s value attribute holds the return value. 当协同程序完成执行并返回时,迭代器引发StopIteration,异常的value属性保存返回值。If the coroutine raises an exception, it is propagated by the iterator. 如果协同例程引发异常,则由迭代器进行传播。Coroutines should not directly raise unhandled StopIteration exceptions.协同例程不应直接引发未经处理的StopIteration异常。

Coroutines also have the methods listed below, which are analogous to those of generators (see Generator-iterator methods). 协同例程还有下面列出的方法,这些方法类似于生成器的方法(请参见生成器迭代器方法)。However, unlike generators, coroutines do not directly support iteration.然而,与生成器不同,协同程序不直接支持迭代。

Changed in version 3.5.2: 版本3.5.2中更改:It is a RuntimeError to await on a coroutine more than once.多次等待协同路由等待的是一个RuntimeError

coroutine.send(value)

Starts or resumes execution of the coroutine. 启动或恢复协同例程的执行。If value is None, this is equivalent to advancing the iterator returned by __await__(). 如果valueNone,这相当于推进由__await__()返回的迭代器。If value is not None, this method delegates to the send() method of the iterator that caused the coroutine to suspend. 如果value不是None,则此方法将委托给导致协同例程挂起的迭代器的send()方法。The result (return value, StopIteration, or other exception) is the same as when iterating over the __await__() return value, described above.结果(返回值、StopIteration或其他异常)与在上面描述的__await__()返回值上迭代时的结果相同。

coroutine.throw(value)
coroutine.throw(type[, value[, traceback]])

Raises the specified exception in the coroutine. 在协同例程中引发指定的异常。This method delegates to the throw() method of the iterator that caused the coroutine to suspend, if it has such a method. Otherwise, the exception is raised at the suspension point. 这个方法委托给迭代器的throw()方法,如果它有这样一个方法,那么这个方法会导致协同例程挂起。否则,将在挂起点引发异常。The result (return value, StopIteration, or other exception) is the same as when iterating over the __await__() return value, described above. 结果(返回值、StopIteration或其他异常)与在上面描述的__await__()返回值上迭代时的结果相同。If the exception is not caught in the coroutine, it propagates back to the caller.如果在协同例程中没有捕获到异常,那么它会传播回调用方。

coroutine.close()

Causes the coroutine to clean itself up and exit. 使协同程序自行清理并退出。If the coroutine is suspended, this method first delegates to the close() method of the iterator that caused the coroutine to suspend, if it has such a method. 如果协程被挂起,此方法首先委托给导致协程挂起的迭代器的close()方法(如果它有这样的方法)。Then it raises GeneratorExit at the suspension point, causing the coroutine to immediately clean itself up. 然后,它在暂停点引发GeneratorExit,导致协同例程立即清理自身。Finally, the coroutine is marked as having finished executing, even if it was never started.最后,协同程序被标记为已完成执行,即使它从未启动过。

Coroutine objects are automatically closed using the above process when they are about to be destroyed.在即将销毁协同路由对象时,将使用上述过程自动关闭这些对象。

3.4.3. Asynchronous Iterators异步迭代器

An asynchronous iterator can call asynchronous code in its __anext__ method.异步迭代器可以在其__anext__方法中调用异步代码。

Asynchronous iterators can be used in an async for statement.异步迭代器可以在async for语句中使用。

object.__aiter__(self)

Must return an asynchronous iterator object.必须返回异步迭代器对象。

object.__anext__(self)

Must return an awaitable resulting in a next value of the iterator. 必须返回一个可等待的结果,从而生成迭代器的下一个值。Should raise a StopAsyncIteration error when the iteration is over.应在迭代结束时引发StopAsyncIteration错误。

An example of an asynchronous iterable object:异步iterable对象的示例:

class Reader:
async def readline(self):
...
def __aiter__(self):
return self

async def __anext__(self):
val = await self.readline()
if val == b'':
raise StopAsyncIteration
return val

New in version 3.5.版本3.5中新增。

Changed in version 3.7:版本3.7中更改: Prior to Python 3.7, __aiter__() could return an awaitable that would resolve to an asynchronous iterator.在Python 3.7之前,__aiter__()可以返回一个可等待的,它将解析为异步迭代器

Starting with Python 3.7, __aiter__() must return an asynchronous iterator object. 从Python 3.7开始,__aiter__()必须返回异步迭代器对象。Returning anything else will result in a TypeError error.返回任何其他内容都将导致TypeError错误。

3.4.4. Asynchronous Context Managers异步上下文管理器

An asynchronous context manager is a context manager that is able to suspend execution in its __aenter__ and __aexit__ methods.异步上下文管理器是一种上下文管理器,它能够在其__aenter____aexit__方法中暂停执行。

Asynchronous context managers can be used in an async with statement.异步上下文管理器可以在async with语句中使用。

object.__aenter__(self)

Semantically similar to __enter__(), the only difference being that it must return an awaitable.语义上类似于__enter__(),唯一的区别是它必须返回一个awaitable

object.__aexit__(self, exc_type, exc_value, traceback)

Semantically similar to __exit__(), the only difference being that it must return an awaitable.语义上类似于__exit__(),唯一的区别是它必须返回一个awaitable

An example of an asynchronous context manager class:异步上下文管理器类的示例:

class AsyncContextManager:
async def __aenter__(self):
await log('entering context')
async def __aexit__(self, exc_type, exc, tb):
await log('exiting context')

New in version 3.5.版本3.5中新增。

Footnotes

1

It is possible in some cases to change an object’s type, under certain controlled conditions. 在某些情况下,在某些受控条件下,可以更改对象的类型。It generally isn’t a good idea though, since it can lead to some very strange behaviour if it is handled incorrectly.但这通常不是一个好主意,因为如果处理不当,可能会导致一些非常奇怪的行为。

2

The __hash__(), __iter__(), __reversed__(), and __contains__() methods have special handling for this; others will still raise a TypeError, but may do so by relying on the behavior that None is not callable.__hash__()__iter__()__reversed__()、和__contains__()方法对此有特殊处理;其他人仍将引发TypeError,但可能通过依赖None不可调用的行为来实现。

3

“Does not support” here means that the class has no such method, or the method returns NotImplemented. 此处的“不支持”表示该类没有此类方法,或者该方法返回NotImplementedDo not set the method to None if you want to force fallback to the right operand’s reflected method—that will instead have the opposite effect of explicitly blocking such fallback.如果要强制回退到右操作数的反射方法,则不要将该方法设置为None,否则会产生显式阻止此类回退的相反效果。

4

For operands of the same type, it is assumed that if the non-reflected method对于相同类型的操作数,假定如果非反射方法such as 譬如__add__()fails then the overall operation is not supported, which is why the reflected method is not called.如果失败,则不支持整个操作,这就是为什么不调用反射的方法。