gpt4 book ai didi

Python 函数及其 __call__ 属性

转载 作者:太空狗 更新时间:2023-10-29 18:05:01 25 4
gpt4 key购买 nike

我正在使用 Python 2.7.2。我想了解调用函数和调用函数的 __call__ 属性之间的关系。例如,考虑以下代码

def foo():
return 5
print foo() # ==> 5
print foo.__call__() # ==> 5

foo.__call__ = lambda : 6
print foo() # ==> 5
print foo.__call__() # ==> 6

前四行似乎表明调用函数foo 与调用foo__call__ 属性相同。然而,最后三行似乎表明它们是不同的野兽,因为我更改了 __call__ 属性,但它没有更改调用 foo() 返回的值.

谁能解释一下调用foo()和调用foo.__call__()之间的关系?有没有办法修改函数的行为,使 foo()foo.__call__() 现在返回 6 而不是 5?

最佳答案

我建议您阅读 special method lookup for new-style classes (尤其是最后一段)。

For new-style 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.

关于Python 函数及其 __call__ 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9707600/

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