我之所以说在 import module 时,类定义中的__new__和__init__会被先执行是有例子的,参见下面的代码,
在主程序第一条语句(语句 1)之前,语句 2 和语句 3 就先被执行了,也就说__new__和__init__方法在执行主程序之前就执行了。我的理解对么?
<p>class MyType(type): </p>
<p> def __init__(self, what, bases=None, dict=None): </p>
<p> super().__init__(what, bases, dict)
</p><p> print("call MyType.__init__()") #语句 3
</p><p> def __new__(cls, name, bases, attrs):
</p><p> print("call MyType.__new__()") #语句 2
</p><p> return type.__new__(cls, name, bases, attrs)
</p><p> def __call__(self, *args, **kwargs):
</p><p> print("MyType.__call__ ")
</p><p> obj = self.__new__(self, *args, **kwargs)
</p><p> self.__init__(obj)
</p><p>class Foo(object, metaclass=MyType):
</p><p> def __init__(self, name=None):
</p><p>
self.name = name
</p><p> print("Foo.__init__ self=", self)
</p><p> def __new__(cls, *args, **kwargs):
</p><p> print("Foo.__new__ cls=", cls)
</p><p> return(object.__new__(cls, *args, **kwargs))
</p><p> def __call__(self, cls):
</p><p> print("Foo.__call__ cls=", cls)
</p><p>
</p><p>
</p><p>if __name__ == '__main__':
</p><p> print("---------test1---------") #语句 1
</p><p> obj2=Foo()</p><p>
</p><p>输出如下:
</p><p>call MyType.__new__()
</p><p>call MyType.__init__()
</p><p>---------test1---------
</p><p>MyType.__call__
</p><p>Foo.__new__ cls= <class '__main__.Foo'>
</p><p>Foo.__init__ self= <__main__.Foo object at 0x01C2B2B0>
</p>