Python metaclass and pythonmetaclass
Meta-classes are generally used to create classes. When executing the class definition, the interpreter must know the correct metadata of the class. The interpreter first looks for the class property _ metaclass __. if this property exists, it is assigned to this class as its Meta class. If this attribute is not defined, it looks up _ metaclass _ in the parent class __. if the _ metaclass _ attribute is not found, the interpreter checks the global variable named _ metaclass _. If it exists, it is used as a metaclass. Otherwise, this class is a traditional class and uses types. ClassType as its metadata class.
When defining an execution class, the correct (usually the default) Meta class will be checked. The Meta class (usually) will pass three parameters (to the constructor): Class Name, inherit the data tuples from the base class and the (class) attribute dictionary.
When will the metadata be 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 _) # question hovertree. comprint '4. class Foo f1 instantiation 'f1 = Foo () print '5. class Foo f2 instantiation 'f2 = Foo () print 'end'
Output result:
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 during the class declaration, the _ metaclass _ method is executed. Later, when defining class objects, only the _ init _ () method of the class is called __() method. _ init _ () in MetaClass is executed only once during class declaration.
From Python core programming
Recommended: http://www.cnblogs.com/roucheng/p/pythonyunsuan.html