Python 为什么在隐式的getitem调用上不调用getattribute?
在尝试包装任意对象时,我遇到了字典和列表的问题。通过调查,我成功地找到了一段简单的代码,我完全不理解它的行为。我希望你们中的一些人能告诉我发生了什么:Python 为什么在隐式的getitem调用上不调用getattribute?,python,magic-methods,Python,Magic Methods,在尝试包装任意对象时,我遇到了字典和列表的问题。通过调查,我成功地找到了一段简单的代码,我完全不理解它的行为。我希望你们中的一些人能告诉我发生了什么: >>> class Cl(object): # simple class that prints (and suppresses) each attribute lookup ... def __getattribute__(self, name): ... print 'Access:', name ... &g
>>> 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__'
>>类Cl(对象):#打印(并抑制)每个属性查找的简单类
... def uu getattribute_uu(self,name):
... 打印“访问权限:”,名称
...
>>>i=Cl()#类的实例
>>>i.test#测试uu getattribute uuu覆盖是否有效
访问:测试
>>>i.uu getitem_uu#测试它是否也适用于特殊功能
访问权限:\uu getitem__
>>>我['foo']#但为什么这不起作用?
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
TypeError:“Cl”对象没有属性“\uuuu getitem\uuuu”
Magic\uuuuu方法()
经过特殊处理:它们被内部分配到类型数据结构中的“插槽”以加快查找速度,并且只在这些插槽中查找它们。如果插槽为空,则会收到收到的错误消息
有关更多详细信息,请参阅文档中的。摘录:
除了为了正确性而绕过任何实例属性外,隐式特殊方法查找通常也会绕过对象元类的\uuu getattribute\uuu()
方法
[……]
以这种方式绕过\uuuu getattribute\uuuu()
机器,为解释器内的速度优化提供了很大的空间,但代价是在处理特殊方法时有一定的灵活性(必须在类对象本身上设置特殊方法,以便解释器一致地调用)
答案中的链接不再有效。这是一个具有版本绑定的较新版本:。