object.__getattribute__ 如何避免 RuntimeError?

How does object.__getattribute__ avoid a RuntimeError?

在极少数情况下,object 的 __getattribute__ 方法必须被覆盖,一个常见的错误是尝试 return 有问题的属性,如下所示:

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__ 承诺的功能。即使超类链被遍历到 object,在行的末尾,某人最终将不得不 return self.something,并且通过定义属性引用必须首先通过 child 的 __getattribute__ 方法。

Python 如何解决这个递归问题?在 object.__getattribute__ 中,如何在不循环进入另一个请求的情况下 return 进行编辑?

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__ 的后代 class 实现。 object.__getattribute__ 是默认的属性访问实现,它始终通过默认的属性访问机制执行其工作。

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