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
相关产品推荐
相关产品推荐

