Metaclass Case Analysis

Metaclass Case

Metaclass Case

class Mytype(type):
    print("Mytype")
    def __new__(cls, *args, **kwargs):
        print("Mytye_new")
        return type.__new__(cls,*args, **kwargs)
class Model(metaclass=Mytype):
    print("Model")
    def __new__(cls, *args, **kwargs):
        print("Model_new")
    x=1
class zx(Model):
    print("zx")
    def __new__(cls, *args, **kwargs):
        print("zx_new")
z=zx("s","sa")
Mytype
Model
Mytye_new
zx
Mytye_new
zx_new

Case Analysis

First view, the results are not what you think completely different, and why Mytype the __new__implementation of the two?

First, the code is self-executing down

First write code execution order, without regard to the details metaclass

##具体参数不详细填写
##主要分为以下7步骤
1 Mytype=type()
2 Model=Mytype()
3 zx=Mytype()
4 z=zx()

Detailed step by step to resolve

1 Mytype=type()

1.执行Mytype=type(),会首先运行一下类的内容,`print("Mytype")`执行了
2.元类是type,首先调用type as type2元类的`__call__()`
3.type2的`__call__()`会调用type的`__new__()和__call__()`方法
4.成功创建了Mytype对象

Print information

Mytype

2 Model=Mytype()

1.执行Model=Mytype(),会首先运行一下类的内容,`print("Model")`执行了
2.元类是Mytype,首先调用type元类的`__call__()`
3.type的`__call__()`会调用Mytype的`__new__()和__call__()`方法,`__new__()`里的` print("Mytye_new")`执行了
4.成功创建了Model对象

Print information

Model
Mytye_new

3 zx=Mytype()

It should be noted that, zx parent is Model, Model metaclass is Mytype, so zx metaclass is Mytype, Yuan class can be inherited, it will execute zx = Mytype ()

1.执行zx=Mytype(),会首先运行一下类的内容,`print("zx")`执行了
2.元类是Mytype,首先调用type元类的`__call__()`
3.type的`__call__()`会调用Mytype的`__new__()和__call__()`方法,`__new__()`里的` print("Mytye_new")`执行了
4.成功创建了zx对象

Print information

zx
Mytye_new

Zx z = 4 ()

1.执行zx=Mytype(),会首先运行一下类的内容,`print("zx_new")`执行了
2.元类是zx,首先调用zx元类的type的`__call__()`
3.type的`__call__()`会调用zx的`__new__()和__call__()`方法,`__new__()`里的` print("zx_new")`执行了
4.成功创建了zx对象

Print information

zx_new

At last

Concrete steps like that, and print the results of the same

Guess you like

Origin www.cnblogs.com/zx125/p/11608852.html