class A(object):
def __init__(self, obj):
self.__obj = obj
def __str__(self):
return str(self.__obj)
__repr__ = __str__
def __getattribute__(self, attr):
return getattr(self.__obj, attr)
A().append(1) #RuntimeError: maximum recursion depth exceeded while calling a Python object
已知:
- 如果在__getattribute__里执行的是诸如 return self.attr 这样的操作,肯定会造成死循环,因为每一次执行 self.attr 都会调用外层的__getattribute__方法,然后一直循环。
不解:
- 上面给出的代码在__getattribute__里面执行的是返回 self.__obj 中的 attr 也就是说执行的是 self.__obj.attr ,跟外层的__getattribute__是两个完全不同的同名方法,并不冲突,不明白为什么还是出现了死循环。