The creation of the class
Refers to say class class itself, for example, the following code:
class Foo:
def __init__(self):
pass
It refers to the Foo
creation process, not Foo
an instance.
1. Analytical MRO
Record (Resolving MRO entries)
According to MRO
the rules to resolve inheritance
2. 确定元类(Determining the appropriate metaclass)
Find metaclass of course follow these rules:
-
And if no base class is not specified
metaclass
, is usedtype()
-
If you specify
metaclass
and it is nottype()
an instance, the direct usemetaclass
-
If the specified
type()
instancemetaclass
, or a base class, (the most derived metaclass is used . ??)
3. Prepare the namespace (Preparing the class namespace)
When determining metaclass, namespace class may be determined. If the meta-class has __prepare__
attributes, then namespace = metaclass.__prepare__(name, bases, **kwargs)
, or namespace is initialized to empty orderly map (empty ordered mapping.)
4. Perform Class
the statement (Executing the class body)
Statements within the class through exec(body, globals(), namespace)
to execution. Normal exec()
is different is that the class definition at an internal function and an outer layer which can access the current scope.
Even within the class of functions defined, the method can not access the interior of the scope of the class. Defined in the class variable be accessed through an object instance of the class or classes, or by __class__
.
5. Create a class object (Creating the class object)
After the above steps, through metaclass(name, bases, namespace, **kwargs)
to create the class.
on __init__
The above steps is to create a class of its own. For example example at the beginning of the above steps just created Foo
, __init__
is executed after the class is instantiated, f = Foo()
this time will be performed__init__