类创建过程

本篇文章用于记录类创建过程相关的文档,可以为以后相关博文的编写提供材料。先在这里做文档备份。

官方文档:https://docs.python.org/3.8/reference/datamodel.html#customizing-class-creation

Python Cookbook 9.15具体内容:
Adding optional keyword arguments to a metaclass requires that you understand all of the steps involved in class creation, because the extra arguments are passed to every method involved. The _prepare_() method is called first and used to create the class namespace prior to the body of any class definition being processed. Normally, this method simply returns a dictionary or other mapping object. The _new_() method is used to instantiate the resulting type object. It is called after the class body has been fully executed. The _init_() method is called last and used to perform any additional initialization steps.
When writing metaclasses, it is somewhat common to only define a _new_() or _init_() method, but not both. However, if extra keyword arguments are going to be accepted, then both methods must be provided and given compatible signatures. The default _prepare_() method accepts any set of keyword arguments, but ignores them. You only need to define it yourself if the extra arguments would somehow affect man‐ agement of the class namespace creation.
The use of keyword-only arguments in this recipe reflects the fact that such arguments will only be supplied by keyword during class creation.

posted @ 2020-02-29 19:30  Jeffrey_Yang  阅读(251)  评论(0编辑  收藏  举报