3. 数据模型

3.1. 对象、值及类型

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

每个对象都有标识、类型和值。对象的 identity 从不改变,一旦创造;可以把它想像成对象的内存地址。 is ‘ operator compares the identity of two objects; the id() 函数返回其标识的表示整数。

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

An object’s type determines the operations that the object supports (e.g., “does it have a length?”) and also defines the possible values for objects of that type. The type() function returns an object’s type (which is an object itself). Like its identity, an object’s type 也是不可变的。 [1]

The value of some objects can change. Objects whose value can change are said to be 可变 ; 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 实现细节: CPython currently uses a reference-counting scheme with (optional) delayed detection of cyclically linked garbage, which collects most objects as soon as they become unreachable, but is not guaranteed to collect garbage containing circular references. See the documentation of the gc module for information on controlling the collection of cyclic garbage. Other implementations act differently and CPython may change. Do not depend on immediate finalization of objects when they become unreachable (so you should always close files explicitly).

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

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

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. (Note that c = d = [] assigns the same object to both c and d )。

3.2. 标准类型层次结构

Below is a list of the types that are built into Python. Extension modules (written in C, Java, or other languages, depending on the implementation) can define additional types. 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.

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 . 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 . 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.) Its truth value is true.

实现算术运算 了解更多细节。

Ellipsis

This type has a single value. There is a single object with this value. This object is accessed through the literal ... 或内置名称 Ellipsis 。其真值为 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 distinguishes between integers, floating point numbers, and complex numbers:

numbers.Integral

These represent elements from the mathematical set of integers (positive and negative).

有 2 种整数类型:

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.

Booleans ( bool )

These represent the truth values False and True. The two objects representing the values False and True are the only Boolean objects. 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" 被分别返回。

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. 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.

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 .

序列

These represent finite ordered sets indexed by non-negative numbers. The built-in function len() returns the number of items of a sequence. When the length of a sequence is n , the index set contains the numbers 0, 1, ..., n -1. Item i of sequence a is selected by a[i] .

Sequences also support slicing: a[i:j] selects all items with index k 这样 i <= k < j . When 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.

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 .

序列根据其可变性来区分:

不可变序列

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.)

下列类型是不可变序列:

字符串

A string is a sequence of values that represent Unicode code points. All the code points in the range U+0000 - U+10FFFF can be represented in a string. Python doesn’t have a char type; instead, every code point in the string is represented as a string object with length 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. 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.

元组

The items of a tuple are arbitrary Python objects. 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.

字节

A bytes object is an immutable array. The items are 8-bit bytes, represented by integers in the range 0 <= x < 256. Bytes literals (like b'abc' ) and the built-in function bytes() can be used to construct bytes objects. Also, bytes objects can be decoded to strings via the decode() 方法。

可变序列

Mutable sequences can be changed after they are created. The subscription and slicing notations can be used as the target of assignment and del (删除) 语句。

There are currently two intrinsic mutable sequence types:

列表

The items of a list are arbitrary Python objects. 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.)

字节数组

A bytearray object is a mutable array. They are created by the built-in bytearray() constructor. Aside from being mutable (and hence unhashable), byte arrays otherwise provide the same interface and functionality as immutable bytes objects.

扩展模块 array 提供可变序列类型的额外范例,就像 collections 模块。

集类型

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. 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.

There are currently two intrinsic set types:

设置

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() .

冻结集

These represent an immutable set. They are created by the built-in frozenset() constructor. As a frozenset is immutable and hashable , it can be used again as an element of another set, or as a dictionary key.

映射

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. The built-in function len() returns the number of items in a mapping.

There is currently a single intrinsic mapping type:

字典

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.

字典是可变的;可以创建它们通过 {...} 表示法 (见章节 字典显示 ).

扩展模块 dbm.ndbm and dbm.gnu 提供额外映射类型范例,就像 collections 模块。

可调用类型

这些类型,其函数调用操作 (见章节 调用 ) 可被应用:

用户定义函数

用户定义函数对象通过函数定义创建 (见章节 函数定义 )。应该采用包含如函数形式参数列表相同项数的自变量列表,调用函数。

特殊属性:

属性 含义  
__doc__ The function’s documentation string, or None if unavailable; not inherited by 子类 可写
__name__ 函数的名称 可写
__qualname__

函数的 合格名称

3.3 版新增。

可写
__module__ The name of the module the function was defined in, or None 若不可用。 可写
__defaults__ A tuple containing default argument values for those arguments that have defaults, or None if no arguments have a default value 可写
__code__ The code object representing the compiled function body. 可写
__globals__ A reference to the dictionary that holds the function’s global variables — the global namespace of the module in which the function 有定义。 只读
__dict__ The namespace supporting arbitrary function 属性。 可写
__closure__ None or a tuple of cells that contain bindings for the function’s free variables. 只读
__annotations__ A dict containing annotations of parameters. The keys of the dict are the parameter names, and 'return' for the return annotation, if provided. 可写
__kwdefaults__ A dict containing defaults for keyword-only parameters. 可写

Most of the attributes labelled “Writable” check the type of the assigned value.

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.

Additional information about a function’s definition can be retrieved from its code object; see the description of internal types below.

实例方法

实例方法对象组合类、类实例及任何可调用对象 (通常是用户定义函数)。

特殊只读属性: __self__ 是类实例对象, __func__ 是函数对象; __doc__ 方法的文档编制 (如同 __func__.__doc__ ); __name__ 是方法名称 (如同 __func__.__name__ ); __module__ 是在其中定义方法的模块名称,或 None 若不可用。

方法还支持访问 (但不设置) 底层函数对象的任意函数属性。

可以创建用户定义的方法对象,当获取类属性时 (可能凭借该类的实例),若该属性是用户定义函数对象或类方法对象。

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. The new method’s __func__ attribute is the original function object.

When a user-defined method object is created by retrieving another method object from a class or instance, the behaviour is the same as for a function object, except that the __func__ attribute of the new instance is not the original method object but its __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.

When an instance method object is called, the underlying function ( __func__ ) is called, inserting the class instance ( __self__ ) in front of the argument list. For instance, when C is a class which contains a definition for a function f() ,和 x 是实例化的 C ,调用 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) 相当于调用 f(C,1) where f is the underlying function.

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.

生成器函数

A function or method which uses the yield statement (see section yield 语句 ) is called a generator 函数 . 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. 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.

协程函数

A function or method which is defined using async def is called a 协程函数 . Such a function, when called, returns a 协程 对象。它可能包含 await 表达式,及 async with and async for statements. See also the 协程对象 章节。

内置函数

内置函数对象是围绕 C 函数的包裹器。例如,内置函数 len() and math.sin() ( math 是标准内置模块)。自变量的数值和类型由 C 函数确定。特殊只读属性: __doc__ 是函数的文档编制字符串,或 None 若不可用; __name__ 是函数的名称; __self__ 被设为 None (但请参阅下一项); __module__ 是在其中定义函数的模块名称或 None 若不可用。

内置方法

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. An example of a built-in method is alist.append() , assuming alist is a list object. In this case, the special read-only attribute __self__ is set to the object denoted by alist .

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__() 且在典型情况下, __init__() to initialize the new instance.
类实例
可以使任意类实例可调用,通过定义 __call__() 方法在其类中。
模块

模块是 Python 代码的基本组织单元,且创建通过 导入系统 作为援引通过 import statement (see import ), or by calling functions such as 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). Attribute references are translated to lookups in this dictionary, e.g., 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).

属性赋值更新模块的名称空间字典,如, m.x = 1 相当于 m.__dict__["x"] = 1 .

特殊只读属性: __dict__ 是模块的名称空间作为字典对象。

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. To avoid this, copy the dictionary or keep the module around while using its dictionary directly.

预定义 (可写) 属性: __name__ 是模块的名称; __doc__ 是模块的文档编制字符串,或 None 若不可用; __file__ is 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; for extension modules loaded dynamically from a shared library, it is the pathname of the shared library file.

自定义类

Custom class types are typically created by class definitions (see section 类定义 ). A class has a namespace implemented by a dictionary object. Class attribute references are translated to lookups in this dictionary, e.g., C.x 会被翻译成 C.__dict__["x"] (although there are a number of hooks which allow for other means of locating attributes). 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. 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/ .

当类属性引用 (对于类 C , say) would yield a class method object, it is transformed into an instance method object whose __self__ attributes is C . When it would yield a static method object, it is transformed into the object wrapped by the static method object. See section 实现描述符 for another way in which attributes retrieved from a class may differ from those actually contained in its __dict__ .

类属性赋值更新类的字典,而不是基类的字典。

可以调用类对象 (见上文) 以产生类实例 (见下文)。

特殊属性: __name__ 是类名; __module__ 是在其中定义类的模块名称; __dict__ 是包含类名称空间的字典; __bases__ 是包含基类的元组,按它们在基类列表中的出现次序; __doc__ is the class’s documentation string, or None 若未定义。

类实例

类实例的创建是通过调用类对象 (见上文)。类实例拥有作为字典实现的名称空间,是搜索属性引用的最初位置。当在那里找不到属性,且实例的类拥有该名称的属性时,将继续搜索类属性。若发现类属性是用户定义函数对象,则将它变换成实例方法对象,其 __self__ 属性是实例。还会变换静态方法和类方法对象;见上文类下内容。见章节 实现描述符 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__ . If no class attribute is found, and the object’s class has a __getattr__() method, that is called to satisfy the lookup.

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.

类实例可以伪装成数字、序列或映射,若它们拥有具有某些特殊名称的方法。见章节 特殊方法名称 .

特殊属性: __dict__ 是属性字典; __class__ 是实例的类。

I/O 对象 (又称文件对象)

A 文件对象 represents an open file. Various shortcuts are available to create file objects: the open() built-in function, and also os.popen() , os.fdopen() ,和 makefile() method of socket objects (and perhaps by other functions or methods provided by extension modules).

对象 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 抽象类。

内部类型

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.

代码对象

代码对象表示 byte-compiled 可执行 Python 代码,或 bytecode . 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.

特殊只读属性: co_name 给出函数名称; co_argcount is the number of positional 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 是包含由字节码所用名称的元组; 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 (including local variables); co_flags is an integer encoding a number of flags for the interpreter.

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.

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.

Other bits in co_flags are reserved for internal use.

若代码对象表示函数,第一项在 co_consts 是函数的文档编制字符串,或 None 若未定义。

帧对象

Frame objects represent execution frames. They may occur in traceback objects (see below).

特殊只读属性: f_back 是前一堆栈帧 (朝向调用者),或 None 若这是底部堆栈帧; f_code 是在此帧中要执行的代码对象; f_locals 是用于查找局部变量的字典; f_globals 用于全局变量; f_builtins 用于内置 (内在) 名称; f_lasti 给出准确指令 (这是代码对象的字节码字符串的索引)。

特殊可写属性: f_trace ,若不 None , is a function called at the start of each source code line (this is used by the debugger); 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.

帧对象支持一方法:

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 被引发若帧目前正被执行。

3.4 版新增。

回溯对象

Traceback objects represent a stack trace of an exception. A traceback object is created when an exception occurs. 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 try 语句 .) It is accessible as the third item of the tuple returned by sys.exc_info() . 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 .

特殊只读属性: 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_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. 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.

切片对象

切片对象用于表示切片对于 __getitem__() 方法。它们还被创建通过内置 slice() 函数。

特殊只读属性: start 是下界; stop 是上界; step 是步幅值;每个为 None 若省略。这些属性可以是任何类型。

切片对象支持一方法:

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. It returns a tuple of three integers; respectively these are the start and stop indices and the step or stride length of the slice. Missing or out-of-bounds indices are handled in a manner consistent with regular slices.

静态方法对象
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 not themselves callable, although the objects they wrap usually are. Static method objects are created by the built-in staticmethod() 构造函数。
类方法对象
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() 构造函数。

3.3. 特殊方法名称

类可以定义具有特殊名称的方法,以实现通过特殊句法援引的某些操作 (譬如:算术运算、下标及切片)。这是 Python 方式的 运算符重载 ,允许类根据语言运算符定义自己的行为。例如,若类定义的方法名为 __getitem__() ,和 x 是此类的实例,那么 x[i] 大致相当于 type(x).__getitem__(x, i) 。除非提及,试图执行操作会引发异常,当未定义合适方法时 (通常是 AttributeError or TypeError ).

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.)

3.3.1. 基本定制

对象。 __new__ ( cls [ , ... ] )

被调用以创建新的实例化类 cls . __new__() 是静态方法 (特殊情况,所以不需要声明它像这样),接收实例的类作为其第一自变量。其余自变量是传递给对象构造函数表达式 (对类的调用) 的那些。返回值对于 __new__() 应该是新的对象实例 (通常是实例化的 cls ).

典型实现创建新的实例化类,通过援引超类的 __new__() 方法使用 super().__new__(cls[, ...]) 采用适当自变量,然后修改新近创建的实例如有必要 (在返回它之前)。

__new__() 返回实例化的 cls ,那么新实例的 __init__() 方法会被援引像 __init__(self[, ...]) ,其中 self is the new instance and the remaining arguments are the same as were passed to __new__() .

__new__() 不返回实例化的 cls ,那么新实例的 __init__() 方法将不会被援引。

__new__() 主要旨在允许子类化不可变类型 (像 int、str、或元组) 以定制实例创建。通常也在自定义元类中覆写它,为定制类创建。

对象。 __init__ ( self [ , ... ] )

被调用在创建实例后 (通过 __new__() ), 但在将它返回给调用者之前。自变量是传递给类构造函数表达式的那些。若基类有 __init__() 方法,派生类的 __init__() 方法 (若有的话) 必须被明确调用,以确保正确初始化实例的基类部分;例如: super().__init__([args...]) .

因为 __new__() and __init__() 工作在一起以构建对象 ( __new__() 用于创建它,而 __init__() 用于定制它),不是非 None 值可能被返回由 __init__() ;这样做会导致 TypeError 在运行时被引发。

对象。 __del__ ( self )

Called when the instance is about to be destroyed. This is also called a destructor. If a base class has a __del__() 方法,派生类的 __del__() method, if any, must explicitly call it to ensure proper deletion of the base class part of the instance. Note that it is possible (though not recommended!) for the __del__() method to postpone destruction of the instance by creating a new reference to it. It may then be called at a later time when this new reference is deleted. It is not guaranteed that __del__() 方法会被调用对于仍存在的对象而言,当解释器退出时。

注意

del x 不直接调用 x.__del__() — 前者递减引用计数为 x 按 1,和后者才被调用在 x ‘s reference count reaches zero. Some common situations that may prevent the reference count of an object from going to zero include: circular references between objects (e.g., a doubly-linked list or a tree data structure with parent and child pointers); a reference to the object on the stack frame of a function that caught an exception (the traceback stored in sys.exc_info()[2] keeps the stack frame alive); or a reference to the object on the stack frame that raised an unhandled exception in interactive mode (the traceback stored in sys.last_traceback keeps the stack frame alive). The first situation can only be remedied by explicitly breaking the cycles; the second can be resolved by freeing the reference to the traceback object when it is no longer useful, and the third can be resolved by storing None in sys.last_traceback . Circular references which are garbage are detected and cleaned up when the cyclic garbage collector is enabled (it’s on by default). Refer to the documentation for the gc module for more information about this topic.

警告

由于在不牢靠情况下 __del__() 方法被援引,在其执行期间出现的异常会被忽略,且警告会被打印到 sys.stderr instead. Also, when __del__() is invoked in response to a module being deleted (e.g., when execution of the program is done), other globals referenced by the __del__() method may already have been deleted or in the process of being torn down (e.g. the import machinery shutting down). For this reason, __del__() methods should do the absolute minimum needed to maintain external invariants. Starting with version 1.5, Python 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__() 方法被调用。

对象。 __repr__ ( self )

被调用通过 repr() built-in function to compute the “official” string representation of an object. 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). If this is not possible, a string of the form <...some useful description...> should be returned. The return value must be a string object. If a class defines __repr__() 而非 __str__() ,那么 __repr__() is also used when an “informal” string representation of instances of that class is required.

This is typically used for debugging, so it is important that the representation is information-rich and unambiguous.

对象。 __str__ ( self )

被调用通过 str(object) 和内置函数 format() and print() to compute the “informal” or nicely printable string representation of an object. The return value must be a string 对象。

此方法不同于 object.__repr__() in that there is no expectation that __str__() return a valid Python expression: a more convenient or concise representation can be used.

The default implementation defined by the built-in type object 调用 object.__repr__() .

对象。 __bytes__ ( self )

被调用通过 bytes() to compute a byte-string representation of an object. This should return a bytes 对象。

对象。 __format__ ( self , format_spec )

被调用通过 format() built-in function (and by extension, the str.format() method of class str ) to produce a “formatted” string representation of an object. The format_spec argument is a string that contains a description of the formatting options desired. 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.

格式规范迷你语言 for a description of the standard formatting syntax.

返回值必须是字符串对象。

3.4 版改变: __format__ 方法的 object 本身引发 TypeError 若传递任何非空字符串。

对象。 __lt__ ( self , other )
对象。 __le__ ( self , other )
对象。 __eq__ ( self , other )
对象。 __ne__ ( self , other )
对象。 __gt__ ( self , other )
对象。 __ge__ ( self , other )

These are the so-called “rich comparison” methods. The correspondence between operator symbols and method names is as follows: x<y 调用 x.__lt__(y) , x<=y 调用 x.__le__(y) , x==y 调用 x.__eq__(y) , x!=y 调用 x.__ne__(y) , x>y 调用 x.__gt__(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. By convention, False and True are returned for a successful comparison. 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 语句),Python 会调用 bool() on the value to determine if the result is true or false.

默认情况下, __ne__() 委托 __eq__() and inverts the result unless it is NotImplemented . There are no other implied relationships among the comparison operators, for example, the truth of (x<y or x==y) does not imply x<=y . To automatically generate ordering operations from a single root operation, see 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.

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. 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.

对象。 __hash__ ( self )

调用通过内置函数 hash() and for operations on members of hashed collections including set , frozenset ,和 dict . __hash__() should return an integer. 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))
								

注意

hash() truncates the value returned from an object’s custom __hash__() method to the size of a Py_ssize_t . This is typically 8 bytes on 64-bit builds and 4 bytes on 32-bit builds. If an object’s __hash__() must interoperate on builds of different bit sizes, be sure to check the width on all supported builds. An easy way to do this is with python -c "import sys; print(sys.hash_info.width)" .

若类未定义 __eq__() 方法,它就不应该定义 __hash__() operation either; if it defines __eq__() 而非 __hash__() , its instances will not be usable as items in hashable collections. 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__() 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) .

A class that overrides __eq__() and does not define __hash__() will have its __hash__() implicitly set to None 。当 __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.Hashable) .

若类覆写 __eq__() needs to retain the implementation of __hash__() from a parent class, the interpreter must be told this explicitly by setting __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. A class which defines its own __hash__() that explicitly raises a TypeError would be incorrectly identified as hashable by an isinstance(obj, collections.Hashable) 调用。

注意

默认情况下, __hash__() values of str, bytes and datetime objects are “salted” with an unpredictable random value. Although they remain constant within an individual Python process, they are not predictable between repeated invocations of 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(n^2) complexity. See http://www.ocert.org/advisories/ocert-2011-003.html 了解细节。

Changing hash values affects the iteration order of dicts, sets and other mappings. Python has never made guarantees about this ordering (and it typically varies between 32-bit and 64-bit builds).

另请参阅 PYTHONHASHSEED .

3.3 版改变: 默认情况下启用哈希随机化。

对象。 __bool__ ( self )

Called to implement truth value testing and the built-in operation bool() ; should return False or True . When this method is not defined, __len__() is called, if it is defined, and the object is considered true if its result is nonzero. If a class defines neither __len__() nor __bool__() , all its instances are considered true.

3.3.2. 定制属性访问

The following methods can be defined to customize the meaning of attribute access (use of, assignment to, or deletion of x.name ) 对于类实例。

对象。 __getattr__ ( self , name )

Called when an attribute lookup has not found the attribute in the usual places (i.e. it is not an instance attribute nor is it found in the class tree for self ). name is the attribute name. This method should return the (computed) attribute value or raise an AttributeError 异常。

Note that if the attribute is found through the normal mechanism, __getattr__() is not called. (This is an intentional asymmetry between __getattr__() and __setattr__() .) This is done both for efficiency reasons and because otherwise __getattr__() would have no way to access other attributes of the instance. 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__ ( 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 . This method should return the (computed) attribute value or raise an AttributeError exception. 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) .

注意

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 特殊方法查找 .

对象。 __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.

__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) .

对象。 __delattr__ ( self , name )

__setattr__() but for attribute deletion instead of assignment. This should only be implemented if del obj.name is meaningful for the object.

对象。 __dir__ ( self )

被调用当 dir() is called on the object. A sequence must be returned. dir() converts the returned sequence to a list and sorts it.

3.3.2.1. 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). In the examples below, “the attribute” refers to the attribute whose name is the key of the property in the owner class’ __dict__ .

对象。 __get__ ( self , instance , owner )

Called to get the attribute of the owner class (class attribute access) or of an instance of that class (instance attribute access). owner is always the owner class, while instance is the instance that the attribute was accessed through, or None when the attribute is accessed through the owner . This method should return the (computed) attribute value or raise an AttributeError 异常。

对象。 __set__ ( self , instance , value )

Called to set the attribute on an instance instance of the owner class to a new value, value .

对象。 __delete__ ( self , instance )

Called to delete the attribute on an instance instance of the owner class.

属性 __objclass__ 的解释是通过 inspect module as specifying the class where this object was defined (setting this appropriately can assist in runtime introspection of dynamic class attributes). 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).

3.3.2.2. 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__() ,和 __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'] ,那么 type(a).__dict__['x'] , and continuing through the base classes of type(a) excluding metaclasses.

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. 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 . How the arguments are assembled depends on a :

直接调用
The simplest and least common call is when user code directly invokes a descriptor method: x.__get__(a) .
实例绑定
若绑定到对象实例, a.x 被变换成调用: type(a).__dict__['x'].__get__(a, type(a)) .
类绑定
若绑定到类, A.x 被变换成调用: A.__dict__['x'].__get__(None, A) .
超级绑定
a 是实例化的 super ,那么绑定 super(B, obj).m() 搜索 obj.__class__.__mro__ 对于基类 A 立即之前 B and then invokes the descriptor with the call: A.__dict__['m'].__get__(obj, obj.__class__) .

For instance bindings, the precedence of descriptor invocation depends on the which descriptor methods are defined. A descriptor can define any combination of __get__() , __set__() and __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. If the descriptor defines __set__() and/or __delete__() , it is a data descriptor; if it defines neither, it is a non-data descriptor. Normally, data descriptors define both __get__() and __set__() , while non-data descriptors have just the __get__() method. Data descriptors with __set__() and __get__() defined always override a redefinition in an instance dictionary. In contrast, non-data descriptors can be overridden by instances.

Python 方法 (包括 staticmethod() and classmethod() ) are implemented as non-data descriptors. 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. Accordingly, instances cannot override the behavior of a property.

3.3.2.3. __slots__

By default, instances of classes have a dictionary for attribute storage. This wastes space for objects having very few instance variables. The space consumption can become acute when creating large numbers of instances.

The default can be overridden by defining __slots__ in a class definition. The __slots__ declaration takes a sequence of instance variables and reserves just enough space in each instance to hold a value for each variable. Space is saved because __dict__ is not created for each instance.

对象。 __slots__

This class variable can be assigned a string, iterable, or sequence of strings with variable names used by instances. __slots__ reserves space for the declared variables and prevents the automatic creation of __dict__ and __weakref__ for each instance.

3.3.2.3.1. Notes on using __slots__
  • When inheriting from a class without __slots__ __dict__ attribute of that class will always be accessible, so a __slots__ definition in the subclass is meaningless.
  • Without a __dict__ variable, instances cannot be assigned new variables not listed in the __slots__ definition. Attempts to assign to an unlisted variable name raises AttributeError . If dynamic assignment of new variables is desired, then add '__dict__' to the sequence of strings in the __slots__ 声明。
  • Without a __weakref__ variable for each instance, classes defining __slots__ do not support weak references to its instances. If weak reference support is needed, then add '__weakref__' to the sequence of strings in the __slots__ 声明。
  • __slots__ are implemented at the class level by creating descriptors ( 实现描述符 ) for each variable name. 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 赋值。
  • The action of a __slots__ declaration is limited to the class where it is defined. As a result, subclasses will have a __dict__ unless they also define __slots__ (which must only contain names of any additional 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 .
  • Any non-string iterable may be assigned to __slots__ . Mappings may also be used; however, in the future, special meaning may be assigned to the values corresponding to each key.
  • __class__ assignment works only if both classes have the same __slots__ .

3.3.3. 定制类创建

默认情况下,类的构造是使用 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) .

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. In the following example, both MyClass and MySubclass 是实例化的 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:

  • the appropriate metaclass is determined
  • the class namespace is prepared
  • the class body is executed
  • the class object is created

3.3.3.1. 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
  • if an explicit metaclass is given and it is not 实例化的 type() , then it is used directly as the metaclass
  • if an instance of type() is given as the explicit metaclass, or bases are defined, then the most derived metaclass is used

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. 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 .

3.3.3.2. 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__ attribute, then the class namespace is initialised as an empty dict() 实例。

另请参阅

PEP 3115 - Python 3000 的元类
引入 __prepare__ 名称空间挂钩

3.3.3.3. Executing the class body

The class body is executed (approximately) as 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.

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, and cannot be accessed at all from static methods.

3.3.3.4. 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__ ).

This class object is the one that will be referenced by the zero-argument form of super() . __class__ is an implicit closure reference created by the compiler if any methods in a class body refer to either __class__ or super . 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.

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 standard Python dictionary and the original object is discarded. The new copy becomes the __dict__ attribute of the class object.

另请参阅

PEP 3135 - 新超级
描述隐式 __class__ 闭包参考

3.3.3.5. Metaclass example

The potential uses for metaclasses are boundless. Some ideas that have been explored include logging, interface checking, automatic delegation, automatic property creation, proxies, frameworks, and automatic resource locking/synchronization.

Here is an example of a metaclass that uses an collections.OrderedDict to remember the order that class variables are defined:

class OrderedClass(type):
    @classmethod
    def __prepare__(metacls, name, bases, **kwds):
        return collections.OrderedDict()
    def __new__(cls, name, bases, namespace, **kwds):
        result = type.__new__(cls, name, bases, dict(namespace))
        result.members = tuple(namespace)
        return result
class A(metaclass=OrderedClass):
    def one(self): pass
    def two(self): pass
    def three(self): pass
    def four(self): pass
>>> A.members
('__module__', 'one', 'two', 'three', 'four')
				

When the class definition for A gets executed, the process begins with calling the metaclass’s __prepare__() method which returns an empty collections.OrderedDict . That mapping records the methods and attributes of A as they are defined within the body of the class statement. Once those definitions are executed, the ordered dictionary is fully populated and the metaclass’s __new__() method gets invoked. That method builds the new type and it saves the ordered dictionary keys in an attribute called members .

3.3.4. 定制实例和子类校验

The following methods are used to override the default behavior of the isinstance() and issubclass() 内置函数。

尤其,元类 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.

类。 __instancecheck__ ( self , instance )

返回 True 若 instance 应被 (直接或间接) 认为是实例化的 class 。若有定义,调用以实现 isinstance(instance, class) .

类。 __subclasscheck__ ( self , subclass )

返回 True 若 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.

另请参阅

PEP 3119 - 引入 ABC (抽象基类)
包括规范为定制 isinstance() and issubclass() 行为透过 __instancecheck__() and __subclasscheck__() , with motivation for this functionality in the context of adding Abstract Base Classes (see the abc 模块) 到语言。

3.3.5. 模拟可调用对象

对象。 __call__ ( self [ , args... ] )

被调用当按函数 "调用" 实例时;若有定义此方法, x(arg1, arg2, ...) is a shorthand for x.__call__(arg1, arg2, ...) .

3.3.6. 模拟容器类型

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. 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 其中 0 <= k < N where N is the length of the sequence, or slice objects, which define a range of items. It is also recommended that mappings provide the methods keys() , values() , items() , get() , clear() , setdefault() , pop() , popitem() , copy() ,和 update() behaving similar to those for Python’s standard dictionary objects. The collections 模块提供 MutableMapping abstract base class to help create those methods from a base set of __getitem__() , __setitem__() , __delitem__() ,和 keys() . Mutable sequences should provide methods append() , count() , index() , extend() , insert() , pop() , remove() , reverse() and sort() , like Python standard list objects. 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. 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. It is further recommended that both mappings and sequences implement the __iter__() method to allow efficient iteration through the container; for mappings, __iter__() should be the same as keys() ; for sequences, it should iterate through the values.

对象。 __len__ ( self )

Called to implement the built-in function len() . Should return the length of the object, an integer >= 0. Also, an object that doesn’t define a __bool__() method and whose __len__() method returns zero is considered to be false in a Boolean context.

CPython 实现细节: In CPython, the length is required to be at most sys.maxsize . If the length is larger than sys.maxsize some features (such as len() ) 可能引发 OverflowError . To prevent raising OverflowError by truth value testing, an object must define a __bool__() 方法。

对象。 __length_hint__ ( self )

Called to implement 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. This method is purely an optimization and is never required for correctness.

3.4 版新增。

注意

Slicing is done exclusively with the following three methods. A call like

a[1:2] = b
					

会被翻译成

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

and so forth. Missing slice items are always filled in with None .

对象。 __getitem__ ( self , key )

Called to implement evaluation of 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__() 方法。若 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. For mapping types, if key is missing (not in the container), KeyError should be raised.

注意

for loops expect that an IndexError will be raised for illegal indexes to allow proper detection of the end of the sequence.

对象。 __missing__ ( self , key )

被调用通过 dict . __getitem__() 以实现 self[key] for dict subclasses when key is not in the dictionary.

对象。 __setitem__ ( self , key , value )

调用以实现赋值 self[key] . Same note as for __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__() 方法。

对象。 __delitem__ ( self , key )

Called to implement deletion of self[key] . Same note as for __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__() 方法。

对象。 __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.

Iterator objects also need to implement this method; they are required to return themselves. For more information on iterator objects, see 迭代器类型 .

对象。 __reversed__ ( self )

被调用 (若存在) 通过 reversed() built-in to implement reverse iteration. It should return a new iterator object that iterates over all the objects in the container in reverse order.

__reversed__() method is not provided, the reversed() built-in will fall back to using the sequence protocol ( __len__() and __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() .

The membership test operators ( in and not in ) are normally implemented as an iteration through a sequence. However, container objects can supply the following special method with a more efficient implementation, which also does not require the object be a sequence.

对象。 __contains__ ( self , item )

Called to implement membership test operators. Should return true if item 是在 self , false otherwise. For mapping objects, this should consider the keys of the mapping rather than the values or the key-item pairs.

若对象未定义 __contains__() ,成员资格测试首先试着迭代凭借 __iter__() ,然后是旧的序列迭代协议凭借 __getitem__() ,见 语言参考中的此节 .

3.3.7. 模拟数值类型

可以定义下列方法,以模拟数值对象。特定种类数字实现 (如:非整数按位操作) 不支持的对应操作方法,应保持未定义。

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

调用这些方法能实现二进制算术运算 ( + , - , * , @ , / , // , % , divmod() , pow() , ** , << , >> , & , ^ , | )。例如,要评估表达式 x + y ,其中 x 是实例化的类拥有 __add__() 方法, x.__add__(y) 被调用。 __divmod__() 方法应该是相当于使用 __floordiv__() and __mod__() ; it should not be related to __truediv__() 。注意, __pow__() should be defined to accept an optional third argument if the ternary version of the built-in pow() function is to be supported.

If one of those methods does not support the operation with the supplied arguments, it should return NotImplemented .

对象。 __radd__ ( self , other )
对象。 __rsub__ ( self , other )
对象。 __rmul__ ( self , other )
对象。 __rmatmul__ ( self , other )
对象。 __rtruediv__ ( self , other )
对象。 __rfloordiv__ ( self , other )
对象。 __rmod__ ( self , other )
对象。 __rdivmod__ ( self , other )
对象。 __rpow__ ( self , other )
对象。 __rlshift__ ( self , other )
对象。 __rrshift__ ( self , other )
对象。 __rand__ ( self , other )
对象。 __rxor__ ( self , other )
对象。 __ror__ ( self , other )

调用这些方法能实现二进制算术运算 ( + , - , * , @ , / , // , % , divmod() , pow() , ** , << , >> , & , ^ , | ) with reflected (swapped) operands. These functions are only called if the left operand does not support the corresponding operation and the operands are of different types. [2] 例如,要评估表达式 x - y ,其中 y 是实例化的类拥有 __rsub__() 方法, y.__rsub__(x) is called if x.__sub__(y) 返回 NotImplemented .

注意,三次 pow() 不会试着调用 __rpow__() (强制转换规则会变得过于复杂)。

注意

If the right operand’s type is a subclass of the left operand’s type and that subclass provides 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.

对象。 __iadd__ ( self , other )
对象。 __isub__ ( self , other )
对象。 __imul__ ( self , other )
对象。 __imatmul__ ( self , other )
对象。 __itruediv__ ( self , other )
对象。 __ifloordiv__ ( self , other )
对象。 __imod__ ( self , other )
对象。 __ipow__ ( self , other [ , modulo ] )
对象。 __ilshift__ ( self , other )
对象。 __irshift__ ( self , other )
对象。 __iand__ ( self , other )
对象。 __ixor__ ( self , other )
对象。 __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 ). 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__() 方法, x += y 相当于 x = x.__iadd__(y) 。否则, x.__add__(y) and y.__radd__(x) are considered, as with the evaluation of 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.

对象。 __neg__ ( self )
对象。 __pos__ ( self )
对象。 __abs__ ( self )
对象。 __invert__ ( self )

被调用以实现一元算术运算 ( - , + , abs() and ~ ).

对象。 __complex__ ( self )
对象。 __int__ ( self )
对象。 __float__ ( self )
对象。 __round__ ( self [ , n ] )

Called to implement the built-in functions complex() , int() , float() and round() . Should return a value of the appropriate type.

对象。 __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). Presence of this method indicates that the numeric object is an integer type. Must return an integer.

注意

In order to have a coherent integer type class, when __index__() is defined __int__() should also be defined, and both should return the same value.

3.3.8. with 语句上下文管理器

A 上下文管理器 is an object that defines the runtime context to be established when executing a with statement. 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 with 语句 ), but can also be used by directly invoking their methods.

Typical uses of context managers include saving and restoring various kinds of global state, locking and unlocking resources, closing opened files, etc.

有关上下文管理器的更多信息,见 上下文管理器类型 .

对象。 __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.

对象。 __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 .

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.

注意, __exit__() methods should not reraise the passed-in exception; this is the caller’s responsibility.

另请参阅

PEP 343 - with 语句
规范、背景及范例为 Python with 语句。

3.3.9. 特殊方法的查找

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:

>>> 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:

>>> 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).

3.4. 协程

3.4.1. 可期待对象

An awaitable 对象一般实现 __await__() 方法。 Coroutine objects returned from async def 函数是可期待的。

注意

The 生成器迭代器 对象返回自生成器装饰采用 types.coroutine() or asyncio.coroutine() 也是可期待的,但它们没有实现 __await__() .

对象。 __await__ ( self )

必须返回 iterator 。应该用于实现 awaitable 对象。例如, asyncio.Future 实现此方法以兼容 await 表达式。

3.5 版新增。

另请参阅

PEP 492 了解 awaitable 对象的有关额外信息。

3.4.2. 协程对象

Coroutine 对象是 awaitable 对象。可以控制协程的执行通过调用 __await__() 并遍历结果。当协程已执行完成并返回时,迭代器引发 StopIteration ,且异常的 value 属性保持返回值。若协程引发异常,通过迭代器传播它。协程不应直接引发未处理 StopIteration 异常。

协程还拥有下文列出方法,类似于生成器的那些 (见 生成器/迭代器方法 ). However, unlike generators, coroutines do not directly support iteration.

3.5.2 版改变: 它是 RuntimeError 以等待协程多次。

coroutine. send ( value )

启动 (或再继续) 协程的执行。若 value is None , this is equivalent to advancing the iterator returned by __await__() 。若 value 不是 None , this method delegates to the send() method of the iterator that caused the coroutine to suspend. The result (return value, StopIteration , or other exception) is the same as when iterating over the __await__() return value, described above.

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. The result (return value, StopIteration , or other exception) is the same as when iterating over the __await__() return value, described above. 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. Then it raises GeneratorExit at the suspension point, causing the coroutine to immediately clean itself up. 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. 异步迭代器

An 异步可迭代 能够调用异步代码在其 __aiter__ implementation, and an 异步迭代器 可以调用异步代码在其 __anext__ 方法。

异步迭代器可用于 async for 语句。

对象。 __aiter__ ( self )

必须返回 异步迭代器 对象。

对象。 __anext__ ( self )

必须返回 awaitable resulting in a next value of the iterator. Should raise a StopAsyncIteration 错误当迭代结束时。

异步可迭代对象范例:

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
					

3.5 版新增。

注意

3.5.2 版改变: Starting with CPython 3.5.2, __aiter__ can directly return asynchronous iterators . Returning an awaitable object will result in a PendingDeprecationWarning .

The recommended way of writing backwards compatible code in CPython 3.5.x is to continue returning awaitables from __aiter__ . If you want to avoid the PendingDeprecationWarning and keep the code backwards compatible, the following decorator can be used:

import functools
import sys
if sys.version_info < (3, 5, 2):
    def aiter_compat(func):
        @functools.wraps(func)
        async def wrapper(self):
            return func(self)
        return wrapper
else:
    def aiter_compat(func):
        return func
					

范例:

class AsyncIterator:
    @aiter_compat
    def __aiter__(self):
        return self
    async def __anext__(self):
        ...
					

从 CPython 3.6 开始, PendingDeprecationWarning will be replaced with the DeprecationWarning . In CPython 3.7, returning an awaitable from __aiter__ will result in a RuntimeError .

3.4.4. 异步上下文管理器

An 异步上下文管理器 上下文管理器 能挂起执行在其 __aenter__ and __aexit__ 方法。

异步上下文管理器可用于 async with 语句。

对象。 __aenter__ ( self )

This method is semantically similar to the __enter__() , with only difference that it must return an awaitable .

对象。 __aexit__ ( self , exc_type , exc_value , traceback )

This method is semantically similar to the __exit__() , with only difference that it must return an awaitable .

异步上下文管理器类范例:

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

3.5 版新增。

脚注

[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] For operands of the same type, it is assumed that if the non-reflected method (譬如 __add__() ) fails the operation is not supported, which is why the reflected method is not called.

内容表

上一话题

2. 词法分析

下一话题

4. 执行模型

本页