Heim  >  Artikel  >  Backend-Entwicklung  >  python的metaclass浅析

python的metaclass浅析

高洛峰
高洛峰Original
2016-10-17 11:51:33957Durchsuche

元类一般用于创建类。在执行类定义时,解释器必须要知道这个类的正确的元类。解释器会先寻找类属性__metaclass__,如果此属性存在,就将这个属性赋值给此类作为它的元类。如果此属性没有定义,它会向上查找父类中的__metaclass__.如果还没有发现__metaclass__属性,解释器会检查名字为__metaclass__的全局变量,如果它存在,就使用它作为元类。否则, 这个类就是一个传统类,并用 types.ClassType 作为此类的元类。

在执行类定义的时候,将检查此类正确的(一般是默认的)元类,元类(通常)传递三个参数(到构造器): 类名,从基类继承数据的元组,和(类的)属性字典。

元类何时被创建?

#!/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'  
输出

结果:


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



可见在类申明的时候,就执行了__metaclass__中的方法了,以后在定义类对象的时候,就只调用该类的__init__()方法,MetaClass中的__init__()只在类申明的时候执行了一次。


Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn