Django中的元類

pythontab發表於2013-12-30

看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: <class '__main__.DeclarativeFieldsMetaclass'>, name: NewBase, bases: (<class '__main__.BaseForm'>,), attrs: {}

cls: <class '__main__.DeclarativeFieldsMetaclass'>, name: Form, bases: (<class '__main__.NewBase'>,), attrs: {'__module__': '__main__'}

cls: <class '__main__.DeclarativeFieldsMetaclass'>, name: MyForm, bases: (<class '__main__.Form'>,), attrs: {'a': 1, '__module__': '__main__', 'b': 2}

 

    雖然沒有直接在程式碼中為MyForm指定metaclass,但由於MyForm繼承自Form,而Form繼承自DeclarativeFieldsMetaclass生成的類名為"NewBase"的類,所以DeclarativeFieldsMetaclass實際上就是MyForm的metaclass。


相關文章