meta-Class (Metaclasses)
The meta-class provides an effective way to change the behavior of Python classes.
The definition of a meta-class is "class of a class". Any instance is its own class, which is a meta-class.
< Span class= "Hljs-class" >class demo: pass obj = Demo () print "class of obj is {0}". Format (obj.__class__) print " class of obj is {0} ". Format (demo.__class__) # class of obj is <class ' __main__.demo ' ># class of obj is &L T;type ' type ';
In the example above, we defined a class demo and generated an object of that class, obj. First, you can see that the __class__ of obj is demo. Interesting to come, then what is the class of the demo? You can see that the __class__ of the demo is type.
So the type is a class of Python class, in other words, obj in the example above is a demo object, and the demo itself is an object of type.
So the type is a meta class, and it is the most common meta class in Python, because it makes the default meta-class for all classes in Python.
Because a meta-class is a class class, it is used to create a class (just as a class is used to create objects). But don't we create classes from a standard class definition? This is true, but Python's internal workings are as follows:
-
- When a class definition is seen, Python collects all the attributes into a dictionary.
- When the class definition ends, Python determines the class's meta-class, and we call it meta.
- Finally, Python executes Meta (name, bases, DCT), Where:
A. Meta is a meta-class, so this call is instantiated.
B. Name is the class name of the new class.
C. Bases is the base class tuple of the new class
D. DCT maps property names to objects, listing all class properties.
So how do you determine the meta-class of a class (a)? Simply put, if a class (a) itself or one of its base classes (BASE_A) has a __metaclass__ attribute present, then this class (A/BASE_A) is the meta-class of Class (a). Otherwise, the type will be a meta-class of Class (A).
Liaoche Python Learning notes-using meta-classes