Python: избегая бесконечных циклов в __getattribute__
Метод__getattribute__
должен быть написан аккуратно, чтобы избежать бесконечного цикла. Например:
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
Следовательно, нам нужно написать метод следующим образом:
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)
Мой вопрос почемуobject.__getattribute__
метод работы? Отсюдаobject
получает__getattribute__
метод? И еслиobject
не имеет никакого__getattribute__
тогда мы просто вызываем один и тот же метод в классеC
но через супер класс. Почему тогда вызов метода через суперкласс не приводит к бесконечному циклу?