A meta class is typically used to create classes. When executing a class definition, the interpreter must know the correct meta-class of the class. The interpreter first looks for the class attribute __metaclass__, and if this attribute exists, assigns the attribute to this class as its meta-class. If this property is not defined, it looks up __metaclass__ in the parent class. If the __metaclass__ attribute is not yet found, the interpreter checks the global variable named __metaclass__ and uses it as a meta-class if it exists. Otherwise, this class is a traditional class and used types. ClassType as a meta-class of this class.
When the class definition is executed, the correct (typically default) meta-class is checked, and the meta-class (usually) passes three parameters (to the constructor): the class name, the tuple that inherits the data from the base class, and the property Dictionary of the (Class).
When was the meta-class created?
#!/usr/bin/env python print ' 1. Metaclass declaration ' class Meta (type): def __init__ (CLS, name, bases, ATTRD): super (META,CLS). __init__ (NAME,BASES,ATTRD) print ' 3. Create class%r '% (name) print ' 2. class Foo declaration ' class Foo (object): __metaclass__=meta def __init__ (self): print ' *. Init class%r '% (self.__class__.__name__) # What asked Hovertree.comprint ' 4. Class Foo F1 instantiation ' f1=foo () print ' 5. Class Foo F2 instantiation ' f2=foo () print ' END ' output
Results:
1. Metaclass Declaration
2. Class Foo Declaration
3. Create class ' Foo '
4. Class Foo F1 instantiation
*. Init class ' Foo '
5. Class Foo F2 instantiation
*. Init class ' Foo '
END
It can be seen that in the class declaration, the __metaclass__ method is executed, and later, when the class object is defined, only the __init__ () method of the class is called, and __init__ () in Metaclass is executed only once at the class declaration.