__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
が、スーパークラスを介しています。なぜ、スーパークラスを介してメソッドを呼び出しても無限ループにならないのですか?