gpt4 book ai didi

python - 为什么 str() 不使用 __getattribute__ 来获取 __str__ 以及如何产生效果?

转载 作者:行者123 更新时间:2023-12-04 02:36:57 24 4
gpt4 key购买 nike

当我打电话时str()在具有重载 __getattribute__ 的对象上方法它似乎没有使用它而是调用 __str__直接地。是否有其他一些我应该修改的功能或让它使用的方法 __getattribute__ ?如果我重载 __str__直接它的行为符合预期,但这并不适合我的需求。

class A(object):
def __getattribute__(self, attr):
if attr == "__str__":
return lambda: "Hello"
return object.__getattribute__(self, attr)

x = A()

print(x)
print(str(x))
print(x.__str__())

输出:
< .位于 0x000001FDF7AEA760 处的对象>
< .位于 0x000001FDF7AEA760 处的对象>
你好

预期输出:
你好
你好
你好

最佳答案

是的,这是 documented behavior :

This method may still be bypassed when looking up special methods as the result of implicit invocation via language syntax or built-in functions.



here :

For custom classes, implicit invocations of special methods are only guaranteed to work correctly if defined on an object’s type, not in the object’s instance dictionary

...

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 - 为什么 str() 不使用 __getattribute__ 来获取 __str__ 以及如何产生效果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61331027/

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