时间:2021-07-01 10:21:17 帮助过:54人阅读
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:
cls:
cls:
虽然没有直接在代码中为MyForm指定metaclass,但由于MyForm继承自Form,而Form继承自DeclarativeFieldsMetaclass生成的类名为"NewBase"的类,所以DeclarativeFieldsMetaclass实际上就是MyForm的metaclass。