This article describes metaclass in details about python. metaclass is 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 will look 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 the metaclass method is executed when the class object is declared. when defining the class object, only the init () method of the class is called, and the init () method in MetaClass () it is executed only once during class declaration.
The above is a detailed description of python metaclass. For more information, see other related articles in the first PHP community!