返回类变量属性时,python __getattribute__ RecursionError

Why does Foo2 result in infinite recursion calling getattr of a class variable in __getattribute__, but Foo works fine making the same call in __getattr__? Any suggestions on how to get Foo2 to work?

class Foobar(object):
    def __init__(self):
        super().__init__()
        self.bar = 5

    def getbar(self):
        return self.bar


class Foo(object):
    def __init__(self):
        super().__init__()
        self.__foo = Foobar()

    def __getattr__(self, attr):
        return getattr(self.__foo, attr)


class Foo2(object):
    def __init__(self):
        super().__init__()
        self.__foo = Foobar()

    def __getattribute__(self, attr):
        try:
            return getattr(self.__foo, attr)
        except AttributeError:
            super().__getattribute__(attr)


if __name__ == '__main__':
    foo = Foo()
    foo2 = Foo2()
    print(foo.bar, foo.getbar())  # Works as expected
    try:
        print(foo2.bar, foo2.getbar())  # Doesn't work
    except RecursionError:
        print('Why does Foo2 result in RecursionError. How to fix?')

设置:Windows 10,Python 3.7

评论