Django中的元类
看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_classclass BaseForm(object): passclass 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。
大数据培训、人工智能培训、Python培训、大数据培训机构、大数据培训班、数据分析培训、大数据可视化培训,就选光环大数据!光环大数据,聘请专业的大数据领域知名讲师,确保教学的整体质量与教学水准。讲师团及时掌握时代潮流技术,将前沿技能融入教学中,确保学生所学知识顺应时代所需。通过深入浅出、通俗易懂的教学方式,指导学生更快的掌握技能知识,成就上万个高薪就业学子。 更多问题咨询,欢迎点击------>>>>在线客服!