看Django(1.6)的Form相關原始碼時比較困惑,於是節選了django.forms.forms.py中的幾個程式碼片段來分析Django中是怎麼使用元類的:
def with_metaclass(meta, *bases): """Create a base class with a metaclass.""" return meta("NewBase", bases, {}) class DeclarativeFieldsMetaclass(type): def __new__(cls, name, bases, attrs): print('cls: %s, name: %s, bases: %s ,attrs: %s\n' % (cls, name, bases, attrs)) new_class = super(DeclarativeFieldsMetaclass, cls).__new__(cls, name, bases, attrs) # new_class._meta = '123' return new_class class BaseForm(object): pass class Form(with_metaclass(DeclarativeFieldsMetaclass, BaseForm)): pass class MyForm(Form): a = 1 b = 2
上面的Python模組,控制台會輸出:cls:
, name: NewBase, bases: (
, name: Form, bases: (
,), rs
, name: MyForm, bases: (
,), attrs: {'a': 1, '__module__': '__main__', 'b': 2}
雖然沒有直接在程式碼中為MyForm指定metaclass,但由於MyForm繼承自Form,而Form繼承自DeclarativeFieldsMetaclass產生的類別名為"NewBase"的類,所以DeclarativeFieldsMetaclass其實就是MyForm的metaclass。