Looking at the form-related source code of Django (1.6), I took a few snippets from django.forms.forms.py to analyze how the meta-class was 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 (Declarativefield Smetaclass, 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 the above Python module, the console will output:
CLS: , Name:newbase, Bases: ( ,), Attrs: {}
CLS: , Name:form, Bases: ( ,), Attrs: {' __module__ ': ' __main__ '}
CLS: , Name:myform, Bases: ( ,), Attrs: {' A ': 1, ' __module__ ': ' __main__ ', ' B ': 2}
Although Metaclass is not specified directly in the code for MyForm, the MyForm inherits from the form and the form inherits from the class named "Newbase" of the Declarativefieldsmetaclass generated class. So Declarativefieldsmetaclass is actually the metaclass of MyForm.