Skip to main content
 首页 » 编程设计

python之object.__getattribute__ 如何避免 RuntimeError

2024年10月17日8insus

在极少数情况下,对象的 __getattribute__方法必须被覆盖,一个常见的错误是像这样尝试并返回有问题的属性:

class WrongWay: 
    def __getattribute__(self, name): 
        # Custom functionality goes here 
        return self.__dict__[name] 

此代码总是产生 RuntimeError由于递归循环,自 self.__dict__本身就是调用相同 __getattribute__ 的属性引用方法。

根据 this answer ,此问题的正确解决方案是将最后一行替换为:

... 
        return super().__getattribute__(self, name) # Defer responsibility to the superclass 

此解决方案在通过 Python 3 解释器运行时有效,但它似乎也违反了 __getattribute__ promise 的功能。即使父类(super class)链遍历到object , 在行尾有人最终必须返回 self. 某事,根据定义,属性引用必须首先通过 child 的 __getattribute__方法。

Python 如何解决这个递归问题?在 object.__getattribute__ ,如何在不循环到另一个请求的情况下返回任何内容?

请您参考如下方法:

at the end of the line somebody will eventually have to return self.something, and by definition that attribute reference must first get through the child's __getattribute__() method.

这是不正确的。 object.__getattribute__ 未定义为返回 self.anything,并且它不尊重 __getattribute__ 的后代类实现。 object.__getattribute__ 是默认的属性访问实现,它始终通过默认的属性访问机制执行其工作。

同样,object.__eq__ 未定义为返回 self == other_thing,并且它不尊重 __eq__ 的后代类实现。 object.__str__ 未定义为返回 str(self),并且它不尊重 __str__ 的后代类实现。 object 的方法是这些方法的默认实现,它们总是做默认的事情。