zoukankan      html  css  js  c++  java
  • Django中的元类

        看Django(1.6)的Form相关源代码时比较迷惑,于是节选了django.forms.forms.py中的几个代码片段来分析Django中是怎么使用元类的:

     1 def with_metaclass(meta, *bases):
     2     """Create a base class with a metaclass."""
     3     return meta("NewBase", bases, {})
     4 
     5 class DeclarativeFieldsMetaclass(type):
     6     def __new__(cls, name, bases, attrs):
     7         print('cls: %s, name: %s, bases: %s ,attrs: %s
    ' % (cls, name, bases, attrs))
     8 
     9         new_class = super(DeclarativeFieldsMetaclass, cls).__new__(cls, name, bases, attrs)
    10 #        new_class._meta = '123'
    11         return new_class
    12 
    13 class BaseForm(object):
    14     pass
    15 
    16 class Form(with_metaclass(DeclarativeFieldsMetaclass, BaseForm)):
    17     pass
    18     
    19 class MyForm(Form):
    20     a = 1
    21     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。

        

  • 相关阅读:
    背包系列 hdu3449 有依赖背包
    背包系列 hdu 3535 分组背包
    屏蔽scrollview的滚动
    高精度算法代码
    输入法出现时,中间固定,底部上移的代码
    排序之分治排序
    排序之双向冒泡排序
    Miller Rabin 大素数测试
    来聊聊WWDC 苹果大会上的那些黑科技
    不想成为好leader的程序猿不是好攻城狮
  • 原文地址:https://www.cnblogs.com/ekswai/p/3491941.html
Copyright © 2011-2022 走看看