【发布时间】:2020-04-24 16:24:42
【问题描述】:
为什么 Foo2 会导致对 __getattribute__ 中的类变量的 getattr 进行无限递归调用,但 Foo 在 __getattr__ 中进行相同调用时工作正常?关于如何让 Foo2 工作的任何建议?
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
【问题讨论】:
-
对于 Foo2,它应该是
__getattr__而不是__getattribute__。
标签: python python-3.x recursion getattr getattribute