小编ret*_*ong的帖子

python3元类的调用顺序

当试图了解metaclass创建类实例的顺序时,我感到困惑。根据此),在此处输入图片说明

我输入以下代码进行验证。

class Meta(type):
    def __call__(self):
        print("Meta __call__")
        super(Meta, self).__call__()

    def __new__(mcs, name, bases, attrs, **kwargs):
        print("Meta __new__")
        return super().__new__(mcs, name, bases, kwargs)

    def __prepare__(msc, name, **kwargs):
        print("Meta __prepare__")
        return {}

class SubMeta(Meta):
    def __call__(self):
        print("SubMeta __call__!")
        super().__call__()

    def __new__(mcs, name, bases, attrs, **kwargs):
        print("SubMeta __new__")
        return super().__new__(mcs, name, bases, kwargs)

    def __prepare__(msc, name, **kwargs):
        print("SubMeta __prepare__")
        return Meta.__prepare__(name, kwargs)

class B(metaclass = SubMeta):
    pass

b = B()
Run Code Online (Sandbox Code Playgroud)

但是,结果似乎不像下面这样。

SubMeta __prepare__
Meta …
Run Code Online (Sandbox Code Playgroud)

python metaclass

5
推荐指数
2
解决办法
638
查看次数

标签 统计

metaclass ×1

python ×1