8.9. types — 动态类型的创建和内置类型的名称

源代码: Lib/types.py


This module defines utility function to assist in dynamic creation of new types.

它还定义用于标准 Python 解释器的一些对象类型的名称,但未暴露作为内置像 int or str are.

最后,它提供了一些不够基础内置的额外类型相关实用类和函数。

8.9.1. 动态类型创建

类型。 new_class ( name , bases=() , kwds=None , exec_body=None )

使用适当元类动态创建类对象。

The first three arguments are the components that make up a class definition header: the class name, the base classes (in order), the keyword arguments (such as metaclass ).

The exec_body argument is a callback that is used to populate the freshly created class namespace. It should accept the class namespace as its sole argument and update the namespace directly with the class contents. If no callback is provided, it has the same effect as passing in lambda ns: ns .

3.3 版新增。

类型。 prepare_class ( name , bases=() , kwds=None )

计算适当元类并创建类名称空间。

The arguments are the components that make up a class definition header: the class name, the base classes (in order) and the keyword arguments (such as metaclass ).

返回值是 3 元组: metaclass, namespace, kwds

metaclass is the appropriate metaclass, namespace is the prepared class namespace and kwds is an updated copy of the passed in kwds argument with any 'metaclass' entry removed. If no kwds argument is passed in, this will be an empty dict.

3.3 版新增。

另请参阅

定制类创建
由这些函数支持的类的创建过程的完整细节
PEP 3115 - Python 3000 的元类
引入 __prepare__ 名称空间挂钩

8.9.2. 标准解释器类型

此模块为实现 Python 解释器要求的许多类型提供名称。它故意避免包括在处理期间偶然出现的一些类型,譬如 listiterator 类型。

这些名称的典型用法是进行 isinstance() or issubclass() 校验。

下列类型是定义的标准名称:

类型。 FunctionType
类型。 LambdaType

用户定义函数和函数的类型,创建通过 lambda 表达式。

类型。 GeneratorType

类型对于 generator 迭代器对象,由生成器函数创建。

类型。 CoroutineType

类型对于 协程 对象,创建通过 async def 函数。

3.5 版新增。

类型。 CodeType

The type for code objects such as returned by compile() .

类型。 MethodType

用户定义类实例方法的类型。

类型。 BuiltinFunctionType
类型。 BuiltinMethodType

内置函数的类型像 len() or sys.exit() , and methods of built-in classes. (Here, the term “built-in” means “written in C”.)

class 类型。 ModuleType ( name , doc=None )

类型对于 模块 . Constructor takes the name of the module to be created and optionally its docstring .

注意

使用 importlib.util.module_from_spec() to create a new module if you wish to set the various import-controlled attributes.

__doc__

The docstring 对于模块。默认为 None .

__loader__

The loader which loaded the module. Defaults to None .

3.4 版改变: 默认为 None 。先前,属性是可选的。

__name__

The name of the module.

__package__

Which a module belongs to. If the module is top-level (i.e. not a part of any specific package) then the attribute should be set to '' , else it should be set to the name of the package (which can be __name__ if the module is a package itself). Defaults to None .

3.4 版改变: 默认为 None 。先前,属性是可选的。

类型。 TracebackType

The type of traceback objects such as found in sys.exc_info()[2] .

类型。 FrameType

The type of frame objects such as found in tb.tb_frame if tb is a traceback object.

类型。 GetSetDescriptorType

The type of objects defined in extension modules with PyGetSetDef ,譬如 FrameType.f_locals or array.array.typecode . This type is used as descriptor for object attributes; it has the same purpose as the property type, but for classes defined in extension modules.

类型。 MemberDescriptorType

The type of objects defined in extension modules with PyMemberDef ,譬如 datetime.timedelta.days . This type is used as descriptor for simple C data members which use standard conversion functions; it has the same purpose as the property type, but for classes defined in extension modules.

CPython 实现细节: In other implementations of Python, this type may be identical to GetSetDescriptorType .

class 类型。 MappingProxyType ( 映射 )

Read-only proxy of a mapping. It provides a dynamic view on the mapping’s entries, which means that when the mapping changes, the view reflects these changes.

3.3 版新增。

key in proxy

返回 True if the underlying mapping has a key key ,否则 False .

proxy[key]

Return the item of the underlying mapping with key key 。引发 KeyError if key is not in the underlying mapping.

iter(proxy)

Return an iterator over the keys of the underlying mapping. This is a shortcut for iter(proxy.keys()) .

len(proxy)

Return the number of items in the underlying mapping.

copy ( )

返回底层映射的浅拷贝。

get ( key [ , default ] )

返回值为 key if key is in the underlying mapping, else default 。若 default 不给定,默认为 None ,因此此方法从不引发 KeyError .

( )

Return a new view of the underlying mapping’s items ( (key, value) 对)。

keys ( )

Return a new view of the underlying mapping’s keys.

( )

Return a new view of the underlying mapping’s values.

8.9.3. 额外实用类和函数

class 类型。 SimpleNamespace

简单 object subclass that provides attribute access to its namespace, as well as a meaningful repr.

不像 object ,采用 SimpleNamespace you can add and remove attributes. If a SimpleNamespace object is initialized with keyword arguments, those are directly added to the underlying namespace.

The type is roughly equivalent to the following code:

class SimpleNamespace:
    def __init__(self, **kwargs):
        self.__dict__.update(kwargs)
    def __repr__(self):
        keys = sorted(self.__dict__)
        items = ("{}={!r}".format(k, self.__dict__[k]) for k in keys)
        return "{}({})".format(type(self).__name__, ", ".join(items))
    def __eq__(self, other):
        return self.__dict__ == other.__dict__
						

SimpleNamespace may be useful as a replacement for class NS: pass . However, for a structured record type use namedtuple() 代替。

3.3 版新增。

类型。 DynamicClassAttribute ( fget=None , fset=None , fdel=None , doc=None )

Route attribute access on a class to __getattr__.

This is a descriptor, used to define attributes that act differently when accessed through an instance and through a class. Instance access remains normal, but access to an attribute through a class will be routed to the class’s __getattr__ method; this is done by raising AttributeError.

This allows one to have properties active on an instance, and have virtual attributes on the class with the same name (see Enum for an example).

3.4 版新增。

8.9.4. 协程实用函数

类型。 协程 ( gen_func )

此函数变换 generator 函数成 协程函数 返回基于生成器的协程。基于生成器的协程仍是 生成器迭代器 ,但也被认为是 协程 对象和 awaitable 。不管怎样,它可能不必实现 __await__() 方法。

gen_func 是生成器函数,它将被原位修改。

gen_func 不是生成器函数,它会被包裹。若它返回实例化 collections.abc.Generator ,实例将包裹在 awaitable 代理对象。所有其它类型对象将按原样返回。

3.5 版新增。

版权所有  © 2014-2026 乐数软件    

工业和信息化部: 粤ICP备14079481号-1