The method __getattribute__
needs to be written carefully in order to avoid the infinite loop. For example:
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
Hence we need to write the method in this way:
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)
My question is why does object.__getattribute__
method work? From where does object
get the __getattribute__
method? And if object
does not have any __getattribute__
, then we are just calling the same method on class C
but via the super class. Why, then calling the method via super class does not result in an infinite loop?
__getattribute__
and not__getattr__
? – Monoplaneobject
does not result in infinite recursion. – Susy__getattribute__
"?a = object(); dir(a)
and you'll see it listed ... – Ambulance