obj = Foo()时,内部魔术方法执行过程:
class MyType(type): def __init__(self,what,bases=None,dict=None): super(MyType, self).__init__(what,bases,dict) print('1.MyType_init') # def __call__(self,*args,**kwargs): # print('2.MyType_call') # r = self.__new__(self, *args, **kwargs) # print('4.',r) # s = self.__init__(self) class Foo(object,metaclass=MyType): def __init__(self): print('5.Foo_init') def __new__(cls,*args, **kwargs): print('3.Foo_new') return object.__new__(cls,*args,**kwargs) def normal_method(self): print('6.普通方法') #Foo() abc = Foo() print(abc)
输出:
1.MyType_init
3.Foo_new
5.Foo_init
<__main__.Foo object at 0x0000029D2679D908>
class MyType(type): def __init__(self,*args, **kwargs): print('1.MyType_init') def __call__(self,*args,**kwargs): print('2.MyType_call') r = self.__new__(self, *args, **kwargs) print('4.',r) s = self.__init__(self) class Foo(object,metaclass=MyType): def __init__(self): print('5.Foo_init') def __new__(cls,*args, **kwargs): print('3.Foo_new') return object.__new__(cls,*args,**kwargs) def normal_method(self): print('6.普通方法') obj = Foo()
输出:
1.MyType_init
2.MyType_call
3.Foo_new
4. <__main__.Foo object at 0x000002571FE6D8D0>
5.Foo_init