1,测试代码

为了查看对象的整个创建流程,编写以下测试代码

class MyType(type):
def __new__(cls, name, bases, attrs):
print("000000000000")
cs=super().__new__(cls, name, bases, attrs)
print(cs,name)
print(attrs)
return cs
def __init__(self,name,bases,attrs):
print("111111111111")
print(self,name)
super().__init__(name,bases,attrs)
print(attrs)
def __call__(self,*args,**kwargs):
print("222222222222")
print(self)
obj=self.__new__(self,*args,**kwargs)
print(obj)
self.__init__(obj,*args,**kwargs)
return obj
class Foo(metaclass=MyType):
def __new__(cls,*args,**kwargs):
print("3333333333333")
obj=super().__new__(cls)
print(obj)
return obj

def __init__(self,name):
print("4444444444444")
self.name=name

f=Foo("xiaoming")
print("aaaaaaaaaaaaaaaaaa")
print(f)
print("bbbbbbbbbbbbbbbbbbb")
print(f.name)
print("cccccccccccccccccccc")
f.name="xiaoqiang"
print("ddddddddddddddddddddddd")
print(f.name)
print("eeeeeeeeeeeeeeeeeeeeeeee")

2,执行结果:

000000000000
<class '__main__.Foo'> Foo
{'__module__': '__main__', '__qualname__': 'Foo', '__new__': <function Foo.__new__ at 0x7f62de02be18>, '__init__': <function Foo.__init__ at 0x7f62de02bea0>, '__classcell__': <cell at 0x7f62de0b5e28: MyType object at 0x2293d58>}
111111111111
<class '__main__.Foo'> Foo
{'__module__': '__main__', '__qualname__': 'Foo', '__new__': <function Foo.__new__ at 0x7f62de02be18>, '__init__': <function Foo.__init__ at 0x7f62de02bea0>, '__classcell__': <cell at 0x7f62de0b5e28: MyType object at 0x2293d58>}
222222222222
<class '__main__.Foo'>
3333333333333
<__main__.Foo object at 0x7f62de03a7f0>
<__main__.Foo object at 0x7f62de03a7f0>
4444444444444
aaaaaaaaaaaaaaaaaa
<__main__.Foo object at 0x7f62de03a7f0>
bbbbbbbbbbbbbbbbbbb
xiaoming
cccccccccccccccccccc

3,画图说明

从以上运行结果可以得出对象在元类的影响和控制下的整个创建以及初始化的流程,用图来说明:

1,执行到f=Foo()时,进入Foo类定义

2,发现Foo类定义有metaclass=MyType参数,于是进入元类MyType

3,执行__new__(cls,name,bases,attrs)方法,创建Foo类cs

4,执行__init__(self,name,bases,attrs)方法,这里的self即上一步的cs,即创建的Foo类

5,执行__call__(self,*args,*kwargs)方法,这里的self即上一步的self,即创建的Foo类

6,使用self调用自身的__new__方法,即调用Foo类的__new__方法,创建Foo类实例对象obj,并返回

7,使用self调用自身的__init__方法,即调用Foo类的__init__方法,初始化实例化对象obj参数

8,返回创建的Foo类实例对象obj给变量f赋值