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

Google Colab中使用__getattribute__等方法引发无限递归错误的原因与解决

错误原因与解决方法

错误原因

你遇到的__getattribute__无限递归,根源在重写的__getattribute__方法里的super().__getattribute__(key)调用:

  • super()函数执行时,需要获取实例的__class__属性来确定父类关系
  • 访问self.__class__会触发你重写的__getattribute__方法
  • 由此形成__getattribute__→super()→访问__class__→__getattribute__的无限循环,最终触发递归错误。

解决方法

将__getattribute__中的super().__getattribute__(key)替换为直接调用object类的__getattribute__方法,绕过super()对__class__的依赖:

修改后的__getattribute__代码:

def __getattribute__(self,key):
    print("In getattribute")
    return object.__getattribute__(self, key)

额外优化

你的__getattr__方法在创建新属性后没有返回对应值,会导致访问新属性时返回None,建议补充返回逻辑:

def __getattr__(self,key):
    print("In getattr")
    y = str(input((f"No attribute found for {key}. Do you want to create one? ")))
    if y.lower() =='y':
      value = str(input("Enter value "))
      self.__setattr__(key,value)
      return value  # 返回新创建的属性值

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 09:31:36