我有以下類試圖定義一個自定義__getattribute__:class Item: def __init__(self): self.x = 1 def __dir__(self): return ['x'] def __getattribute__(self, i): if i not in dir(self): return "NOT DEFINED!" else: return super().__getattribute__(a)然后我可以很好地運行它:>>> i=Item()>>> i.x1>>> i.a'NOT DEFINED!'但是,如果我更改此行:if i not in dir(self):至:if i not in self.__dir__():我得到了一個RecursionError它似乎在自稱的東西。為什么會這樣,為什么dir()和不同__dir__()?
1 回答

弒天下
TA貢獻1818條經驗 獲得超8個贊
__getattribute__
每當在對象上使用點表示法時都會調用該方法,因此會調用self.__dir__()
with作為參數的方法,然后使用您的代碼再次調用該方法,然后使用相同的參數再次調用該方法,從而導致無休止的遞歸.__getattribute__
self
'__dir__'
self.__dir__()
__getattribute__
添加回答
舉報
0/150
提交
取消