在试图包装任意对象时,我遇到了字典和列表的问题。调查之后,我想出了一个简单的代码,它的行为我根本不明白。我希望你们中的一些人能告诉我发生了什么:
>>> 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__'发布于 2012-07-06 10:02:54
魔术__methods__()被特别对待:它们在内部被分配到类型数据结构中的“插槽”,以加快查找速度,并且它们只在这些插槽中被查找。如果插槽为空,则会得到所得到的错误消息。
有关详细信息,请参阅文档中的新样式类的特殊方法查找。节选:
除了为了正确性而绕过任何实例属性之外,隐式特殊方法查找通常也会绕过对象的元类的
__getattribute__()方法。 … 以这种方式绕过__getattribute__()机器为解释器内的速度优化提供了重要的范围,代价是在处理特殊方法方面有一定的灵活性(必须在类对象本身上设置特殊方法,以便解释器一致调用)。
https://stackoverflow.com/questions/11360020
复制相似问题