You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何像调用元类默认__new__那样调用其默认__init__方法?

调用元类的默认__init__方法

当然可以用类似方式调用元类的默认__init__函数,思路和你调用__new__的逻辑一致——因为你的MyMeta继承自type(Python的默认元类),所以通过super()就能调用到type里的__init__,也就是你说的“默认__init__”。

直接在你的__init__方法里加上这行代码就行:

super(MyMeta, cls).__init__(name, bases, namespace, **kwargs)

修改后的完整代码示例:

class MyMeta(type):

    def __new__(cls, name, bases, attr):
        print("MyMeta.__new__ called")
        return super(MyMeta, cls).__new__(cls, name, bases, attr)

    def __init__(cls, name, bases, namespace, **kwargs):
        print("MyMeta.__init__ called")
        # 调用默认元类的__init__方法
        super(MyMeta, cls).__init__(name, bases, namespace, **kwargs)

简单来说,super(MyMeta, cls)会返回MyMeta的父类(也就是type)的代理对象,调用它的__init__就是触发默认元类的初始化逻辑,和你调用__new__的方式完全对应。

内容的提问来源于stack exchange,提问作者user1187968

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 15:31:05