Home  >  Article  >  Backend Development  >  A brief analysis of python’s metaclass

A brief analysis of python’s metaclass

高洛峰
高洛峰Original
2016-10-17 11:51:33955browse

Metaclasses are generally used to create classes. When executing a class definition, the interpreter must know the correct metaclass of the class. The interpreter will first look for the class attribute __metaclass__. If this attribute exists, it will assign this attribute to this class as its metaclass. If this attribute is not defined, it will look up the __metaclass__ in the parent class. If the __metaclass__ attribute is not found yet, the interpreter will check the global variable named __metaclass__ and, if it exists, use it as the metaclass. Otherwise, the class is a traditional class, with types.ClassType as its metaclass.

When executing the class definition, the correct (usually default) metaclass of this class will be checked. The metaclass (usually) passes three parameters (to the constructor): class name, tuple of data inherited from the base class , and the attribute dictionary (of the class).

When is the metaclass 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__)  
   
# 何问起 hovertree.com
print '4. Class Foo f1 instantiation'  
f1=Foo()  
   
print '5. Class Foo f2 instantiation'  
f2=Foo()  
   
print 'END'  
输出

Results:


1. Metaclass declaration

2. Class Foo declaration

3. Create class 'Foo'

4. Class Foo f1 instantiation

*. 5. Class Foo f2 instantiation

*. Init class 'Foo'

END



It can be seen that when the class is declared, the methods in __metaclass__ are executed. Later, when defining the class object time, only the __init__() method of the class is called. __init__() in MetaClass is only executed once when the class is declared.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn