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 method in Metaclass is executed, and later when the class object is defined, only the init () method of the class is called, and Init () in Metaclass executes only once at the time of the class declaration.