首頁 >後端開發 >Python教學 >Django中的元類

Django中的元類

高洛峰
高洛峰原創
2016-10-17 14:03:101501瀏覽

看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: (,), attrs: {}

cls:

, name: Form, bases: (cls:

, name: Form, bases: (

,), rs: {'__module__': '__main__'}

cls:

, name: MyForm, bases: (

,), attrs: {'a': 1, '__module__': '__main__', 'b': 2}

 


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

🎜🎜🎜
陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn