Django中的元类-乾颐堂

时间:2022-07-29 21:13:10

看Django(1.6)的Form相关源代码时比较迷惑,于是节选了django.forms.forms.py中的几个代码片段来分析Django中是怎么使用元类的:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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):
    = 1
    = 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。

http://www.qytang.com/cn/list/28/393.htm
http://www.qytang.com/cn/list/28/391.htm
http://www.qytang.com/cn/list/28/389.htm
http://www.qytang.com/cn/list/28/388.htm
http://www.qytang.com/cn/list/28/362.htm
http://www.qytang.com/cn/list/28/358.htm
http://www.qytang.com/cn/list/28/351.htm
http://www.qytang.com/cn/list/28/348.htm
http://www.qytang.com/cn/list/28/340.htm
http://www.qytang.com/cn/list/28/338.htm
http://www.qytang.com/cn/list/28/336.htm
http://www.qytang.com/cn/list/28/330.htm