对象。 __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, evaluation of 格式化字符串文字 str.format() method, 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 若传递任何非空字符串。

3.7 版改变: object.__format__(x, '') 现在相当于 str(x) 而不是 format(str(x), '') .

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

默认情况下, object 实现 __eq__() 通过使用 is ,返回 NotImplemented in the case of a false comparison: True if x is y else NotImplemented 。对于 __ne__() , by default it delegates to __eq__() and inverts the result unless it is NotImplemented . There 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 . 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 the 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.

When no appropriate method returns any value other than NotImplemented == and != operators will fall back to is and is not ,分别。

对象。 __hash__ ( self )

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

注意

默认情况下, __hash__() values of str and bytes 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://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).

另请参阅 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 the default attribute access fails with an AttributeError (either __getattribute__() 引发 AttributeError 因为 name is not an instance attribute or an attribute in the class tree for self ; or __get__() name property raises AttributeError ). This method should either 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 。见 特殊方法查找 .

For certain sensitive attribute accesses, raises an 审计事件 object.__getattr__ 采用自变量 obj and name .

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

For certain sensitive attribute assignments, raises an 审计事件 object.__setattr__ 采用自变量 obj , 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.

对于某些敏感属性删除,引发 审计事件 object.__delattr__ 采用自变量 obj and name .

对象。 __dir__ ( self )

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

3.3.2.1. 定制模块属性访问

Special names __getattr__ and __dir__ can be also used to customize access to module attributes. 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 . If an attribute is not found on a module object through the normal lookup, i.e. object.__getattribute__() ,那么 __getattr__ is searched in the module __dict__ before raising an AttributeError . If found, it is called with the attribute name and the result is returned.

The __dir__ function should accept no arguments, and return an iterable of strings that represents the names accessible on module. If present, this function overrides the standard dir() search on a module.

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 。例如:

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
													

注意

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.

3.5 版改变: __class__ 模块属性现在可写。

Added in version 3.7: __getattr__ and __dir__ 模块属性。

另请参阅

PEP 562 - Module __getattr__ and __dir__

描述 __getattr__ and __dir__ 函数在模块。

3.3.2.2. 实现描述符

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

This method should return the computed attribute value or raise an AttributeError 异常。

PEP 252 specifies that __get__() is callable with one or two arguments. 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’s own __getattribute__() implementation always passes in both arguments whether they are required or not.

对象。 __set__ ( self , instance , value )

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

注意,添加 __set__() or __delete__() changes the kind of descriptor to a “data descriptor”. See 援引描述符 了解更多细节。

对象。 __delete__ ( self , instance )

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

Instances of descriptors may also have the __objclass__ attribute present:

对象。 __objclass__

属性 __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.3. 援引描述符

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 dotted lookup such as super(A, a).x 搜索 a.__class__.__mro__ for a base class B following A 然后返回 B.__dict__['x'].__get__(a, A) . If not a descriptor, x is returned unchanged.

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__() . 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 __get__() and __set__() (and/or __delete__() ) defined always override a redefinition in an instance dictionary. 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. 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.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.)

The space saved over using __dict__ can be significant. Attribute lookup speed can be significantly improved as well.

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

Notes on using __slots__ :

  • When inheriting from a class without __slots__ __dict__ and __weakref__ attribute of the instances will always be accessible.

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

  • The action of a __slots__ declaration is not limited to the class where it is defined. __slots__ declared in parents are available in child classes. However, child subclasses will get a __dict__ and __weakref__ unless they also define __slots__ (which should 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.

  • TypeError will be raised if nonempty __slots__ are defined for a class derived from a "variable-length" built-in type 譬如 int , bytes ,和 tuple .

  • Any non-string iterable may be assigned to __slots__ .

  • dictionary is used to assign __slots__ , the dictionary keys will be used as the slot names. 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() .

  • __class__ assignment works only if both classes have the same __slots__ .

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

  • iterator is used for __slots__ then a descriptor is created for each of the iterator’s values. However, the __slots__ attribute will be an empty iterator.

3.3.3. 定制类创建

Whenever a class inherits from another class, __init_subclass__() is called on the parent class. 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.

classmethod 对象。 __init_subclass__ ( cls )

This method is called whenever the containing class is subclassed. cls is then the new subclass. 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 class’s __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:

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
																	

默认实现 object.__init_subclass__ 什么都不做,但会引发错误,若以任何自变量调用它。

注意

元类提示 metaclass is consumed by the rest of the type machinery, and is never passed to __init_subclass__ implementations. The actual metaclass (rather than the explicit hint) can be accessed as type(cls) .

Added in version 3.6.

When a class is created, type.__new__() scans the class variables and makes callbacks to those with a __set_name__() 挂钩。

对象。 __set_name__ ( self , owner , name )

Automatically called at the time the owning class owner is created. The object has been assigned to name in that class:

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. If needed, __set_name__() can be called directly:

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

创建类对象 了解更多细节。

Added in version 3.6.

3.3.3.1. 元类

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

  • MRO entries are resolved;

  • the appropriate metaclass is determined;

  • the class namespace is prepared;

  • the class body is executed;

  • the class object is created.

3.3.3.2. 解析 MRO 条目

对象。 __mro_entries__ ( self , bases )

If a base that appears in a class definition is not an instance of type , then an __mro_entries__() method is searched on the base. If an __mro_entries__() method is found, the base is substituted with the result of a call to __mro_entries__() when creating the class. The method is called with the original bases tuple passed to the bases parameter, and must return a tuple of classes that will be used instead of the base. The returned tuple may be empty: in these cases, the original base is ignored.

另请参阅

types.resolve_bases()

Dynamically resolve bases that are not instances of type .

types.get_original_bases()

Retrieve a class’s “original bases” prior to modifications by __mro_entries__() .

PEP 560

Core support for typing module and generic types.

3.3.3.3. 确定适当元类

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.4. 准备类名称空间

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). The __prepare__ method should be implemented as a 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__ attribute, then the class namespace is initialised as an empty ordered mapping.

另请参阅

PEP 3115 - Python 3000 的元类

引入 __prepare__ 名称空间挂钩

3.3.3.5. 执行类本体

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, or through the implicit lexically scoped __class__ reference described in the next section.

3.3.3.6. 创建类对象

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.

CPython 实现细节: In CPython 3.6 and later, the __class__ cell is passed to the metaclass as a __classcell__ entry in the class namespace. If present, this must be propagated up to the type.__new__ call in order for the class to be initialised correctly. Failing to do so will result in a RuntimeError in Python 3.8.

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:

  1. The type.__new__ method collects all of the attributes in the class namespace that define a __set_name__() 方法;

  2. Those __set_name__ methods are called with the class being defined and the assigned name of that particular attribute;

  3. The __init_subclass__() hook is called on the immediate parent of the new class in its method resolution order.

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. The new copy is wrapped in a read-only proxy, which becomes the __dict__ attribute of the class object.

另请参阅

PEP 3135 - 新超级

描述隐式 __class__ 闭包参考

3.3.3.7. 元类的用途

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. 定制实例和子类校验

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 , 子类 )

返回 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__() ,采用此功能动机在上下文添加抽象基类 (见 abc 模块) 到语言。

3.3.5. 模拟一般类型

当使用 类型注解 , it is often useful to parameterize a 一般类型 using Python’s square-brackets notation. For example, the annotation list[int] might be used to signify a list in which all the elements are of type int .

另请参阅

PEP 484 - 类型提示

介绍 Python 的类型注解框架

Generic Alias Types

Documentation for objects representing parameterized generic classes

一般 , 用户定义泛型 and typing.Generic

Documentation on how to implement generic classes that can be parameterized at runtime and understood by static type-checkers.

类可以 generally only be parameterized if it defines the special class method __class_getitem__() .

classmethod 对象。 __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. As such, there is no need for it to be decorated with @classmethod when it is defined.

3.3.5.1. 目的对于 __class_getitem__

目的对于 __class_getitem__() is to allow runtime parameterization of standard-library generic classes in order to more easily apply 类型提示 to these classes.

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__() ,或继承自 typing.Generic , which has its own implementation of __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. Using __class_getitem__() on any class for purposes other than type hinting is discouraged.

3.3.5.2. __class_getitem__ versus __getitem__

通常, subscription of an object using square brackets will call the __getitem__() instance method defined on the object’s class. However, if the object being subscribed is itself a class, the class method __class_getitem__() may be called instead. __class_getitem__() should return a GenericAlias object if it is properly defined.

Presented with the 表达式 obj[x] , the Python interpreter follows something like the following process to decide whether __getitem__() or __class_getitem__() should be called:

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. The class of a class is known as that class’s metaclass , and most classes have the type class as their metaclass. 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:

>>> # 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. An example of this can be found in the 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'>
																				

另请参阅

PEP 560 - Core Support for typing module and generic types

引入 __class_getitem__() , and outlining when a subscription 产生 __class_getitem__() being called instead of __getitem__()

3.3.6. 模拟可调用对象

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

被调用当按函数 "调用" 实例时;若有定义此方法, x(arg1, arg2, ...) 大致翻译成 type(x).__call__(x, arg1, ...) .

3.3.7. 模拟容器类型

The following methods can be defined to implement container objects. Containers usually are sequences (譬如 lists or tuples ) 或 mappings (像 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.abc 模块提供 MutableMapping 抽象基类 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 iterate through the object’s 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. The return value may also be NotImplemented , which is treated the same as if the __length_hint__ method didn’t exist at all. This method is purely an optimization and is never required for correctness.

Added in version 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] 。对于 sequence types, the accepted keys should be integers. Optionally, they may support slice objects as well. Negative index support is also optional. If key is of an inappropriate type, TypeError may be raised; if key is a value outside the set of indexes for the sequence (after any special interpretation of negative values), IndexError should be raised. For 映射 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.

注意

subscripting a class , the special class method __class_getitem__() may be called instead of __getitem__() 。见 __class_getitem__ versus __getitem__ 了解更多细节。

对象。 __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__() 方法。

对象。 __missing__ ( self , key )

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

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

对象。 __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 container. However, container objects can supply the following special method with a more efficient implementation, which also does not require the object be iterable.

对象。 __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.8. 模拟数值类型

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

对象。 __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 [ , ] )
对象。 __lshift__ ( self , other )
对象。 __rshift__ ( self , other )
对象。 __and__ ( self , other )
对象。 __xor__ ( self , other )
对象。 __or__ ( self , other )

调用这些方法能实现二进制算术运算 ( + , - , * , @ , / , // , % , divmod() , pow() , ** , << , >> , & , ^ , | )。例如,要评估表达式 x + y ,其中 x 是实例化的类拥有 __add__() 方法, type(x).__add__(x, 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 [ 3 ] and the operands are of different types. [ 4 ] 例如,要评估表达式 x - y ,其中 y 是实例化的类拥有 __rsub__() 方法, type(y).__rsub__(y, x) is called if type(x).__sub__(x, y) 返回 NotImplemented .

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

注意

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.

对象。 __iadd__ ( self , other )
对象。 __isub__ ( self , other )
对象。 __imul__ ( self , other )
对象。 __imatmul__ ( self , other )
对象。 __itruediv__ ( self , other )
对象。 __ifloordiv__ ( self , other )
对象。 __imod__ ( self , other )
对象。 __ipow__ ( self , other [ , ] )
对象。 __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, or if that method returns NotImplemented , 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) 。若 __iadd__() does not exist, or if x.__iadd__(y) 返回 NotImplemented , 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 )

Called to implement the built-in functions complex() , int() and float() . 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.

__int__() , __float__() and __complex__() are not defined then corresponding built-in functions int() , float() and complex() fall back to __index__() .

对象。 __round__ ( self [ , ndigits ] )
对象。 __trunc__ ( self )
对象。 __floor__ ( self )
对象。 __ceil__ ( self )

Called to implement the built-in function round() and math 函数 trunc() , floor() and ceil() . Unless ndigits 被传递给 __round__() all these methods should return the value of the object truncated to an Integral (typically an int ).

内置函数 int() falls back to __trunc__() if neither __int__() nor __index__() 有定义。

3.11 版改变: The delegation of int() to __trunc__() 被弃用。

3.3.9. 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.10. 定制类模式匹配中的位置自变量

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 . To be able to use that kind of pattern, the class needs to define a __match_args__ 属性。

对象。 __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. The absence of this attribute is equivalent to setting it to () .

例如,若 MyClass.__match_args__ is ("left", "center", "right") that means that 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 .

Added in version 3.10.

另请参阅

PEP 634 - Structural Pattern Matching

The specification for the Python match 语句。

3.3.11. Emulating buffer types

The 缓冲协议 provides a way for Python objects to expose efficient access to a low-level memory array. This protocol is implemented by builtin types such as bytes and memoryview , and third-party libraries may define additional buffer types.

While buffer types are usually implemented in C, it is also possible to implement the protocol in Python.

对象。 __buffer__ ( self , flags )

Called when a buffer is requested from self (for example, by the memoryview constructor). The flags argument is an integer representing the kind of buffer requested, affecting for example whether the returned buffer is read-only or writable. inspect.BufferFlags provides a convenient way to interpret the flags. The method must return a memoryview 对象。

对象。 __release_buffer__ ( self , buffer )

Called when a buffer is no longer needed. The buffer 自变量是 memoryview object that was previously returned by __buffer__() . The method must release any resources associated with the buffer. This method should return None . Buffer objects that do not need to perform any cleanup are not required to implement this method.

3.12 版添加。

另请参阅

PEP 688 - Making the buffer protocol accessible in Python

Introduces the Python __buffer__ and __release_buffer__ 方法。

collections.abc.Buffer

ABC for buffer types.

3.3.12. 特殊方法查找

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__() 方法。 协程对象 返回自 async def 函数是可期待的。

注意

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

对象。 __await__ ( self )

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

注意

The language doesn’t place any restriction on the type or value of the objects yielded by the iterator returned by __await__ , as this is specific to the implementation of the asynchronous execution framework (e.g. asyncio ) that will be managing the awaitable 对象。

Added in version 3.5.

另请参阅

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

3.4.2. 协程对象

协程对象 are 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 ( 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. 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.

Changed in version 3.12: The second signature (type[, value[, traceback]]) is deprecated and may be removed in a future version of Python.

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 异步迭代器 可以调用异步代码在其 __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
																											

Added in version 3.5.

3.7 版改变: Python 3.7 之前, __aiter__() 可以返回 awaitable 会被解析成 异步迭代器 .

从 Python 3.7 开始, __aiter__() must return an asynchronous iterator object. Returning anything else will result in a TypeError 错误。

3.4.4. 异步上下文管理器

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

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

对象。 __aenter__ ( self )

语义上类似于 __enter__() , the only difference being that it must return an awaitable .

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

语义上类似于 __exit__() , the only difference being 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')
																											

Added in version 3.5.

脚注

内容表

上一话题

2. 词法分析

下一话题

4. 执行模型

本页