python的metaclass淺析

pythontab發表於2016-05-31

元類一般用於建立類。在執行類定義時,直譯器必須要知道這個類的正確的元類。直譯器會先尋找類屬性__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__()只在類申明的時候執行了一次。


相關文章