Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I override a method object's __call__ method in Python? [duplicate]

Tags:

python

Here is what I am working with so far

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

I am not interested in another way to achieve the desired output. Rather, for educational purposes, I would like to know why overriding the __call__ as I have done, doesn't work as I expect.

like image 217
John Avatar asked Aug 13 '13 01:08

John


People also ask

How do you override a method in Python?

In Python method overriding occurs by simply defining in the child class a method with the same name of a method in the parent class. When you define a method in the object you make this latter able to satisfy that method call, so the implementations of its ancestors do not come in play.

What does __ call __ do in Python?

The __call__ method enables Python programmers to write classes where the instances behave like functions and can be called like a function. When the instance is called as a function; if this method is defined, x(arg1, arg2, ...) is a shorthand for x. __call__(arg1, arg2, ...) .

What is method overriding in Python explain with example?

What is Method Overriding in Python? Method overriding is a feature of object-oriented programming languages where the subclass or child class can provide the program with specific characteristics or a specific implementation process of data provided that are already defined in the parent class or superclass.

What is __ get __ in Python?

Python __get__ Magic Method. Python's __get__() magic method defines the dynamic return value when accessing a specific instance and class attribute. It is defined in the attribute's class and not in the class holding the attribute (= the owner class).


1 Answers

This appears to be due to special-casing of function types in ceval.c, in call_function:

if (PyFunction_Check(func))
    x = fast_function(func, pp_stack, n, na, nk);
else
    x = do_call(func, pp_stack, na, nk);

I'd guess that this is probably for efficiency, since calling regular functions, and ignoring the __call__ attribute, is by far the most common kind of calling that gets done.

like image 99
Owen Avatar answered Sep 28 '22 14:09

Owen