gpt4 book ai didi

python - 为什么不在隐式 __getitem__ 调用中调用 __getattribute__?

转载 作者:太空狗 更新时间:2023-10-29 20:16:04 25 4
gpt4 key购买 nike

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

>>> 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 - 为什么不在隐式 __getitem__ 调用中调用 __getattribute__?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11360020/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com