metaclass,元類
metaclass是這樣定義的:In object-oriented programming, a metaclass is a class whose instances are classes. Just as an ordinary class defines the behavior of certain objects, a metaclass defines the behavior of certain classes and their instances.
metaclass的執行個體化結果是類,而class執行個體化的結果是instance。metaclass是建立類的模板,所有的類都是通過他來create的(調用__new__),你可以定建立類的獨特行為,實現你所需要的特殊功能。
type 也是metalclass的一種元類。
通過派生type的子類,來實作類別建立過程中的特殊行為。
type的建構函式:type.__new__(cls, name, bases, dct)
- cls: 將要建立的類,類似與self,但是self指向的是instance,而這裡cls指向的是class
- name: 類的名字
- bases: 基類,通常是tuple類型
- attrs: dict類型,就是類的屬性或者函數
實現為類的方法,進行匿名驗證的metaclass, ----AuthenticationDecoratorMeta
源碼:
from types import FunctionTypedef Authentication(func): print 'Execute validition Successfully!' return funcclass AuthenticationDecoratorMeta(type): def __new__(cls, name, bases, dct): for name, value in dct.iteritems(): if name not in ('__metaclass__', '__init__', '__module__') and \ type(value) == FunctionType: value = Authentication(value) dct[name] = value return type.__new__(cls, name, bases, dct) class Login(object): __metaclass__ = AuthenticationDecoratorMeta def Delete(self, x): print 'Delete ', xdef main(): login = Login() login.Delete('xxxx') if __name__ == '__main__': main()
運行效果如下:
Execute validition Successfully!Delete xxxx