Python: evitando loops infinitos em __getattribute__
O método__getattribute__
precisa ser escrito cuidadosamente para evitar o loop infinito. Por exemplo:
class A:
def __init__(self):
self.x = 100
def __getattribute__(self, x):
return self.x
>>> a = A()
>>> a.x # infinite looop
RuntimeError: maximum recursion depth exceeded while calling a Python object
class B:
def __init__(self):
self.x = 100
def __getattribute__(self, x):
return self.__dict__[x]
>>> b = B()
>>> b.x # infinite looop
RuntimeError: maximum recursion depth exceeded while calling a Python object
Por isso, precisamos escrever o método desta maneira:
class C:
def __init__(self):
self.x = 100
def __getattribute__(self, x):
# 1. error
# AttributeError: type object 'object' has no attribute '__getattr__'
# return object.__getattr__(self, x)
# 2. works
return object.__getattribute__(self, x)
# 3. works too
# return super().__getattribute__(x)
Minha pergunta é por queobject.__getattribute__
trabalho de método? De ondeobject
Obtém o__getattribute__
método? E seobject
não tem nenhum__getattribute__
, então estamos apenas chamando o mesmo método na classeC
mas através da super classe. Por que, então, chamar o método via superclasse não resulta em um loop infinito?