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.
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.
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? 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.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With