Python class creation process

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 Foocreation process, not Fooan instance.

1. Analytical MRORecord (Resolving MRO entries)

According to MROthe rules to resolve inheritance

2. 确定元类(Determining the appropriate metaclass)

Find metaclass of course follow these rules:

  1. And if no base class is not specified metaclass, is usedtype()

  2. If you specify metaclassand it is not type()an instance, the direct usemetaclass

  3. If the specified type()instance metaclass, 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 Classthe 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__

Published an original article · won praise 0 · Views 77

Guess you like

Origin blog.csdn.net/matong5418/article/details/104618214