类是元类的实例,默认的元类type派生自object。因此,元类遵循创建object 实例的常规规则 - __new__ 构造实例,__init__ 可以初始化它。
>>> class DemoClass(object):
... def __new__(cls):
... print('__new__ object of DemoClass')
... return super().__new__(cls)
...
... def __init__(self):
... print('__init__ object of DemoClass')
... return super().__init__()
...
>>> demo_instance = DemoClass() # instantiate DemoClass
__new__ object of DemoClass
__init__ object of DemoClass
当我们的类是元类时也会发生同样的情况 - 它仍然是 object 并且行为如此。
>>> class DemoType(type):
... def __new__(mcs, name, bases, attrs):
... print('__new__ object %r of DemoType' % name)
... return super().__new__(mcs, name, bases, attrs)
...
... def __init__(self, name, bases, attrs):
... print('__init__ object %r of DemoType' % name)
... return super().__init__(name, bases, attrs)
...
>>> demo_class = DemoType('demo_class', (), {}) # instantiate DemoType
__new__ object 'demo_class' of DemoType
__init__ object 'demo_class' of DemoType
重申,如果a 是A 的一个实例,那么A.__new__ 用于创建a。这同样适用于类和元类,因为前者是后者的实例。
类不会从其元类继承__new__。一个类有一个元类,元类的__new__ 用于创建类。
当从一个类(元类的实例)继承时,元类也被继承。这意味着子类也是元类的一个实例。因此,元类的__new__ 和__init__ 都用于构造和初始化这个实例。
>>> class DemoClass(metaclass=DemoType):
... ...
...
>>> class DemoSubClass(DemoClass):
... ...
...
__new__ object 'DemoClass' of DemoType
__init__ object 'DemoClass' of DemoType
__new__ object 'DemoSubClass' of DemoType
__init__ object 'DemoSubClass' of DemoType
>>> type(DemoClass) # classes are instances of their metaclass
__main__.DemoType
>>> type(DemoSubClass) # subclasses inherit metaclasses from base classes
__main__.DemoType
这样做的目的是元类存在于define how classes are created。这包括子类。为每个子类调用 __new__ 可以让元类对新的类主体、额外的基类和命名空间以及关键字做出反应。