首页 > 解决方案 > 为什么调用超类`__getattribute__`会导致无限递归?

问题描述

显然,以下将导致无限循环:

class Klaus:
    def __getattribute__(self, key):
        return getattr(type(self), key)

但是,我不明白为什么调用超类__getattribute__会:

class Parent:

    def __init__(self):
        print("begin __init__")
        self._x = 3
        print("end __init__")

    def __getattribute__(self, attr_name):
        superk = super(type(self), self)
        boohl = superk.__getattribute__ == self.__getattribute__
        print("with age comes wisdom", boohl)
        return superk.__getattribute__(attr_name)

class Child(Parent):

    def __getattribute__(self, attr_name):
        superk = super(type(self), self)
        boohl = superk.__getattribute__ == self.__getattribute__
        print("this booger is green!", boohl)
        return super(type(self), self).__getattribute__(attr_name)

obj = Child()
print("lambda")
print(obj._x)
print("anonymous")

标签: pythonpython-3.xinheritanceoverridinggetattribute

解决方案


因为永远type(self)是孩子。即使您在 Parent 的方法中,仍然是 Child 的实例。self

这就是为什么当您使用长格式时,super您必须始终显式使用当前类,而不是 this。当然,在 Python 3 中,super()无论如何您都可以不带任何参数使用。


推荐阅读