9
在试图包装任意对象时,我遇到了字典和列表的问题。调查中,我设法想出了一段简单的代码,其行为我简直不明白。我希望一些你能告诉我是怎么回事:为什么__getattribute__不会对隐式__getitem __-调用调用?
>>> class Cl(object): # simple class that prints (and suppresses) each attribute lookup
... def __getattribute__(self, name):
... print 'Access:', name
...
>>> i = Cl() # instance of class
>>> i.test # test that __getattribute__ override works
Access: test
>>> i.__getitem__ # test that it works for special functions, too
Access: __getitem__
>>> i['foo'] # but why doesn't this work?
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'Cl' object has no attribute '__getitem__'