企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
### 导航 - [索引](../genindex.xhtml "总目录") - [模块](../py-modindex.xhtml "Python 模块索引") | - [下一页](copy.xhtml "copy --- 浅层 (shallow) 和深层 (deep) 复制操作") | - [上一页](weakref.xhtml "weakref --- 弱引用") | - ![](https://box.kancloud.cn/a721fc7ec672275e257bbbfde49a4d4e_16x16.png) - [Python](https://www.python.org/) » - zh\_CN 3.7.3 [文档](../index.xhtml) » - [Python 标准库](index.xhtml) » - [数据类型](datatypes.xhtml) » - $('.inline-search').show(0); | # [`types`](#module-types "types: Names for built-in types.") --- Dynamic type creation and names for built-in types **Source code:** [Lib/types.py](https://github.com/python/cpython/tree/3.7/Lib/types.py) \[https://github.com/python/cpython/tree/3.7/Lib/types.py\] - - - - - - This module defines utility functions to assist in dynamic creation of new types. It also defines names for some object types that are used by the standard Python interpreter, but not exposed as builtins like [`int`](functions.xhtml#int "int") or [`str`](stdtypes.xhtml#str "str") are. Finally, it provides some additional type-related utility classes and functions that are not fundamental enough to be builtins. ## Dynamic Type Creation `types.``new_class`(*name*, *bases=()*, *kwds=None*, *exec\_body=None*)Creates a class object dynamically using the appropriate metaclass. 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 新版功能. `types.``prepare_class`(*name*, *bases=()*, *kwds=None*)Calculates the appropriate metaclass and creates the class namespace. 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`). The return value is a 3-tuple: `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 新版功能. 在 3.6 版更改: The default value for the `namespace` element of the returned tuple has changed. Now an insertion-order-preserving mapping is used when the metaclass does not have a `__prepare__` method. 参见 [元类](../reference/datamodel.xhtml#metaclasses)Full details of the class creation process supported by these functions [**PEP 3115**](https://www.python.org/dev/peps/pep-3115) \[https://www.python.org/dev/peps/pep-3115\] - Python 3000 中的元类引入 `__prepare__` 命名空间钩子 `types.``resolve_bases`(*bases*)Resolve MRO entries dynamically as specified by [**PEP 560**](https://www.python.org/dev/peps/pep-0560) \[https://www.python.org/dev/peps/pep-0560\]. This function looks for items in *bases* that are not instances of [`type`](functions.xhtml#type "type"), and returns a tuple where each such object that has an `__mro_entries__` method is replaced with an unpacked result of calling this method. If a *bases* item is an instance of [`type`](functions.xhtml#type "type"), or it doesn't have an `__mro_entries__` method, then it is included in the return tuple unchanged. 3\.7 新版功能. 参见 [**PEP 560**](https://www.python.org/dev/peps/pep-0560) \[https://www.python.org/dev/peps/pep-0560\] - 对类型模块和泛型类型的核心支持 ## Standard Interpreter Types This module provides names for many of the types that are required to implement a Python interpreter. It deliberately avoids including some of the types that arise only incidentally during processing such as the `listiterator` type. Typical use of these names is for [`isinstance()`](functions.xhtml#isinstance "isinstance") or [`issubclass()`](functions.xhtml#issubclass "issubclass") checks. Standard names are defined for the following types: `types.``FunctionType``types.``LambdaType`用户自定义函数以及由 [`lambda`](../reference/expressions.xhtml#lambda) 表达式所创建函数的类型。 `types.``GeneratorType`[generator](../glossary.xhtml#term-generator) 迭代器对象的类型,由生成器函数创建。 `types.``CoroutineType`[coroutine](../glossary.xhtml#term-coroutine) 对象的类型,由 [`async def`](../reference/compound_stmts.xhtml#async-def) 函数创建。 3\.5 新版功能. `types.``AsyncGeneratorType`[asynchronous generator](../glossary.xhtml#term-asynchronous-generator) 迭代器对象的类型,由异步生成器函数创建。 3\.6 新版功能. `types.``CodeType`The type for code objects such as returned by [`compile()`](functions.xhtml#compile "compile"). `types.``MethodType`The type of methods of user-defined class instances. `types.``BuiltinFunctionType``types.``BuiltinMethodType`The type of built-in functions like [`len()`](functions.xhtml#len "len") or [`sys.exit()`](sys.xhtml#sys.exit "sys.exit"), and methods of built-in classes. (Here, the term "built-in" means "written in C".) `types.``WrapperDescriptorType`The type of methods of some built-in data types and base classes such as [`object.__init__()`](../reference/datamodel.xhtml#object.__init__ "object.__init__") or [`object.__lt__()`](../reference/datamodel.xhtml#object.__lt__ "object.__lt__"). 3\.7 新版功能. `types.``MethodWrapperType`The type of *bound* methods of some built-in data types and base classes. For example it is the type of `object().__str__`. 3\.7 新版功能. `types.``MethodDescriptorType`The type of methods of some built-in data types such as [`str.join()`](stdtypes.xhtml#str.join "str.join"). 3\.7 新版功能. `types.``ClassMethodDescriptorType`The type of *unbound* class methods of some built-in data types such as `dict.__dict__['fromkeys']`. 3\.7 新版功能. *class* `types.``ModuleType`(*name*, *doc=None*)The type of [modules](../glossary.xhtml#term-module). Constructor takes the name of the module to be created and optionally its [docstring](../glossary.xhtml#term-docstring). 注解 Use [`importlib.util.module_from_spec()`](importlib.xhtml#importlib.util.module_from_spec "importlib.util.module_from_spec") to create a new module if you wish to set the various import-controlled attributes. `__doc__`The [docstring](../glossary.xhtml#term-docstring) of the module. Defaults to `None`. `__loader__`The [loader](../glossary.xhtml#term-loader) which loaded the module. Defaults to `None`. 在 3.4 版更改: Defaults to `None`. Previously the attribute was optional. `__name__`The name of the module. `__package__`Which [package](../glossary.xhtml#term-package) 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__`](../reference/import.xhtml#__name__ "__name__") if the module is a package itself). Defaults to `None`. 在 3.4 版更改: Defaults to `None`. Previously the attribute was optional. *class* `types.``TracebackType`(*tb\_next*, *tb\_frame*, *tb\_lasti*, *tb\_lineno*)The type of traceback objects such as found in `sys.exc_info()[2]`. See [the language reference](../reference/datamodel.xhtml#traceback-objects) for details of the available attributes and operations, and guidance on creating tracebacks dynamically. `types.``FrameType`The type of frame objects such as found in `tb.tb_frame` if `tb` is a traceback object. See [the language reference](../reference/datamodel.xhtml#frame-objects) for details of the available attributes and operations. `types.``GetSetDescriptorType`The type of objects defined in extension modules with `PyGetSetDef`, such as `FrameType.f_locals` or `array.array.typecode`. This type is used as descriptor for object attributes; it has the same purpose as the [`property`](functions.xhtml#property "property") type, but for classes defined in extension modules. `types.``MemberDescriptorType`The type of objects defined in extension modules with `PyMemberDef`, such as `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`](functions.xhtml#property "property") type, but for classes defined in extension modules. **CPython implementation detail:** In other implementations of Python, this type may be identical to `GetSetDescriptorType`. *class* `types.``MappingProxyType`(*mapping*)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`Return `True` if the underlying mapping has a key *key*, else `False`. `proxy[key]`Return the item of the underlying mapping with key *key*. Raises a [`KeyError`](exceptions.xhtml#KeyError "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`()Return a shallow copy of the underlying mapping. `get`(*key*\[, *default*\])Return the value for *key* if *key* is in the underlying mapping, else *default*. If *default* is not given, it defaults to `None`, so that this method never raises a [`KeyError`](exceptions.xhtml#KeyError "KeyError"). `items`()Return a new view of the underlying mapping's items (`(key, value)`pairs). `keys`()Return a new view of the underlying mapping's keys. `values`()Return a new view of the underlying mapping's values. ## Additional Utility Classes and Functions *class* `types.``SimpleNamespace`A simple [`object`](functions.xhtml#object "object") subclass that provides attribute access to its namespace, as well as a meaningful repr. Unlike [`object`](functions.xhtml#object "object"), with `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()`](collections.xhtml#collections.namedtuple "collections.namedtuple")instead. 3\.3 新版功能. `types.``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 新版功能. ## Coroutine Utility Functions `types.``coroutine`(*gen\_func*)This function transforms a [generator](../glossary.xhtml#term-generator) function into a [coroutine function](../glossary.xhtml#term-coroutine-function) which returns a generator-based coroutine. The generator-based coroutine is still a [generator iterator](../glossary.xhtml#term-generator-iterator), but is also considered to be a [coroutine](../glossary.xhtml#term-coroutine) object and is [awaitable](../glossary.xhtml#term-awaitable). However, it may not necessarily implement the [`__await__()`](../reference/datamodel.xhtml#object.__await__ "object.__await__") method. If *gen\_func* is a generator function, it will be modified in-place. If *gen\_func* is not a generator function, it will be wrapped. If it returns an instance of [`collections.abc.Generator`](collections.abc.xhtml#collections.abc.Generator "collections.abc.Generator"), the instance will be wrapped in an *awaitable* proxy object. All other types of objects will be returned as is. 3\.5 新版功能. ### 导航 - [索引](../genindex.xhtml "总目录") - [模块](../py-modindex.xhtml "Python 模块索引") | - [下一页](copy.xhtml "copy --- 浅层 (shallow) 和深层 (deep) 复制操作") | - [上一页](weakref.xhtml "weakref --- 弱引用") | - ![](https://box.kancloud.cn/a721fc7ec672275e257bbbfde49a4d4e_16x16.png) - [Python](https://www.python.org/) » - zh\_CN 3.7.3 [文档](../index.xhtml) » - [Python 标准库](index.xhtml) » - [数据类型](datatypes.xhtml) » - $('.inline-search').show(0); | © [版权所有](../copyright.xhtml) 2001-2019, Python Software Foundation. Python 软件基金会是一个非盈利组织。 [请捐助。](https://www.python.org/psf/donations/) 最后更新于 5月 21, 2019. [发现了问题](../bugs.xhtml)? 使用[Sphinx](http://sphinx.pocoo.org/)1.8.4 创建。