Home  >  Article  >  Backend Development  >  Metaclasses in Django

Metaclasses in Django

高洛峰
高洛峰Original
2016-10-17 14:03:101343browse

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: , name: NewBase, bases: (,), attrs: {}

cls: , name: Form, bases: (,), attrs: {'__module__': '__main__'}

cls: , name: MyForm, bases: (,), attrs: {'a': 1, '__module__': '__main__', 'b': 2}

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.


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn