我认为它很难击败 Django 文档对此的说法。
Model 类(参见 base.py)有一个元类属性,它将 ModelBase(也在 base.py 中)定义为用于创建新类的类。所以模型库。调用new来创建这个新的 Example 类。重要的是要意识到我们在这里创建的是类对象,而不是它的实例。换句话说,Python 正在创建最终将绑定到我们当前命名空间中的示例名称的东西。
基本上,元类定义了如何创建类本身。在创建期间,可以将其他属性/方法/任何东西绑定到该类。这个stackoverflow答案给出的例子,大写了一个类的所有属性
# remember that `type` is actually a class like `str` and `int`
# so you can inherit from it
class UpperAttrMetaclass(type):
# __new__ is the method called before __init__
# it's the method that creates the object and returns it
# while __init__ just initializes the object passed as parameter
# you rarely use __new__, except when you want to control how the object
# is created.
# here the created object is the class, and we want to customize it
# so we override __new__
# you can do some stuff in __init__ too if you wish
# some advanced use involves overriding __call__ as well, but we won't
# see this
def __new__(upperattr_metaclass, future_class_name,
future_class_parents, future_class_attr):
attrs = ((name, value) for name, value in future_class_attr.items() if not name.startswith('__'))
uppercase_attr = dict((name.upper(), value) for name, value in attrs)
return type(future_class_name, future_class_parents, uppercase_attr)
以类似的方式,Django 的模型元类可以消化您应用于该类的属性,并添加各种有用的属性用于验证/等,包括偶数方法和非类。