I was confused when looking at the Form-related source code of Django (1.6), so I excerpted several code snippets from django.forms.forms.py to analyze how metaclasses are used in 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
Loading For the above Python module, the console will output:
cls:
cls:
cls:
Although the metaclass is not directly specified for MyForm in the code, because MyForm inherits from Form, and Form inherits from the class named "NewBase" generated by DeclarativeFieldsMetaclass, so DeclarativeFieldsMetaclass is actually MyForm's metaclass.