【问题标题】:Why is __getattribute__ not invoked on an implicit __getitem__-invocation?为什么在隐式 __getitem__ 调用中不调用 __getattribute__?
【发布时间】:2012-07-06 09:59:38
【问题描述】:

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

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

【问题讨论】:

    标签: python magic-methods


    【解决方案1】:

    Magic __methods__() 被特殊对待:它们被内部分配到类型数据结构中的“槽”以加快它们的查找速度,并且它们只在这些槽中查找。如果插槽为空,您会收到错误消息。

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

    除了为了正确性而绕过任何实例属性外,隐式特殊方法查找通常还会绕过对象元类的__getattribute__()方法。

    […]

    以这种方式绕过 __getattribute__() 机制为解释器中的速度优化提供了很大的空间,但代价是处理特殊方法时具有一定的灵活性(特殊方法必须在类对象本身上设置才能被解释器始终调用)。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-15
    • 1970-01-01
    • 1970-01-01
    • 2017-06-22
    • 1970-01-01
    • 1970-01-01
    • 2012-08-04
    相关资源
    最近更新 更多