编程语言
首页 > 编程语言> > python – 为什么在隐式__getitem __-调用时没有调用__getattribute__?

python – 为什么在隐式__getitem __-调用时没有调用__getattribute__?

作者:互联网

在尝试包装任意对象时,我遇到了字典和列表的问题.调查,我设法提出了一段简单的代码,其行为我根本不理解.我希望你们中的一些人可以告诉我发生了什么:

>>> 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__'

解决方法:

Magic __methods __()被特别处理:它们在内部分配给类型数据结构中的“槽”以加速它们的查找,并且它们仅在这些槽中被查找.如果插槽为空,则会收到错误消息.

有关详细信息,请参阅文档中的Special method lookup for new-style classes.摘抄:

In addition to bypassing any instance attributes in the interest of correctness, implicit special method lookup generally also bypasses the __getattribute__() method even of the object’s metaclass.

[…]

Bypassing the __getattribute__() machinery in this fashion provides significant scope for speed optimisations within the interpreter, at the cost of some flexibility in the handling of special methods (the special method must be set on the class object itself in order to be consistently invoked by the interpreter).

标签:python,magic-methods
来源: https://codeday.me/bug/20190930/1836920.html