代码:
class MyType(type): def __init__(self, *args, **kwargs): super(MyType, self).__init__(*args, **kwargs) def __call__(self, *args, **kwargs): obj = self.__new__(self, *args, **kwargs) obj.__init__(*args, **kwargs) return obj class Foo(object, metaclass=MyType): def __init__(self): print(‘xxx‘) obj = Foo() print(obj)
结果
xxx <__main__.Foo object at 0x0000022688A07EB8>
我们看下面的代码
new
class Foo(object): def __init__(self): return ‘init‘ def __new__(cls, *args, **kwargs): return ‘new‘ obj = Foo() print(obj)
结果 :new
class Foo(object): def __init__(self): return ‘init‘ def __new__(cls, *args, **kwargs): return cls.__init__(cls) obj = Foo() print(obj)
结果 init
由此可以看出 实例化对象的过程,__new__()比__init__()先执行
但是 实际上,在这次“”交♂易“”之前还走了一个中间商 那就是type的__call__(),但是我们并看不到__claa__()的源码。
类的metaclass 默认是type。
class MyType(type): def __call__(self, *args, **kwargs): return ‘MyType‘ class Foo(object, metaclass=MyType): def __init__(self): return ‘init‘ def __new__(cls, *args, **kwargs): return cls.__init__(cls) def __call__(self, *args, **kwargs): return ‘call‘ obj = Foo() print(obj)
结果:MyType