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

重写__new__方法并处理参数时遇TypeError问题求助

解决TypeError: object.new() takes exactly one argument问题,同时限制实例仅通过create方法创建

错误根源

你在__new__方法中调用super().__new__(cls, myArg=myArg)时,向object.__new__传递了额外参数,但object.__new__仅接受类对象作为唯一参数,多余参数触发了TypeError。

修正后的实现

import inspect

class MyObject():
    def __new__(cls, *args, **kwargs):
        caller_frame = inspect.stack()[1]
        caller_func = caller_frame.function
        
        if caller_func == "create" and caller_frame.frame.f_locals.get('cls') == cls:
            # 仅传递类对象给父类__new__,参数交给__init__处理
            return super().__new__(cls)
        raise Exception("To create a new MyObject, use MyObject.create().")

    def __init__(self, myArg):
        self.myArg = myArg

    @classmethod
    async def create(cls, myArg="test"):
        # 这里可以添加异步逻辑,比如await database_query()
        return cls(myArg=myArg)

关键调整说明

  • 移除多余参数传递:调用super().__new__时只传cls,初始化参数完全由__init__处理,符合Python实例创建的流程。
  • 兼容任意参数:__new__用*args, **kwargs接收参数,后续新增参数时无需修改__new__。
  • 优化调用检查逻辑:通过caller_frame.function获取调用函数名,比硬编码栈索引更可靠,避免因调用环境变化导致判断失效。
  • 支持异步create:直接用async修饰create方法,调用时使用await MyObject.create(your_arg)即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 12:15:11