<分区>
这是我目前的工作
def f(n):
return n
f.__call__ = lambda n: n + 1
print f(2) #I expect an output of 3 but get an output of 2
我对另一种实现所需输出的方法不感兴趣。相反,出于教育目的,我想知道为什么像我所做的那样重写 __call__
并没有像我预期的那样工作。
标签 python
<分区>
这是我目前的工作
def f(n):
return n
f.__call__ = lambda n: n + 1
print f(2) #I expect an output of 3 but get an output of 2
我对另一种实现所需输出的方法不感兴趣。相反,出于教育目的,我想知道为什么像我所做的那样重写 __call__
并没有像我预期的那样工作。
最佳答案
这似乎是由于 ceval.c 中函数类型的特殊大小写所致, 在 call_function
中:
if (PyFunction_Check(func))
x = fast_function(func, pp_stack, n, na, nk);
else
x = do_call(func, pp_stack, na, nk);
我猜这可能是为了提高效率,因为调用常规函数并忽略 __call__
属性是迄今为止最常见的调用类型。
关于python - 如何在 Python 中覆盖方法对象的 __call__ 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18199347/