引言
在上一篇对BaseForm的源码分析中,还有部分的迷惑没有解决。
Question:
在BaseForm的初始化函数中,可以看到有如下一段代码,究竟self.base_fields从何而来?Form是如何实现Form和Field的结合?
# The base_fields class attribute is the *class-wide* definition of # fields. Because a particular *instance* of the class might want to # alter self.fields, we create self.fields here by copying base_fields. # Instances should always modify self.fields; they should not modify # self.base_fields. self.fields = copy.deepcopy(self.base_fields)
在使用Django Form的时候,继承的是forms.Form而并非BaseForm,为何?
- Conclusion:以上问题都可以通过对Metaclass的分析解决。
Metaclass
首先了解到底什么是Metaclass?推荐这篇文章深刻理解Python中的元类(metaclass) 。
在Python中,一切皆为对象,包括类也是一种对象。既然类是一种对象,那么肯定会有生成类的类,这就是元类(Metaclass),元类负责生成类这种对象。
type()
一般使用type函数来确定函数的类型,但是type函数还发挥了另一个作用:作为元类动态地生成类。
Usage: type(name, base, attr)
Example:
>>> Person = type('Person', (), {
'age': 20, 'gender': 'male'})