Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python functions and their __call__ attribute

Tags:

python

I am using Python 2.7.2. I want to understand the relationship between calling a function and calling the __call__ attribute of the function. For example, consider the following code

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

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

The firsts four lines seem to indicate the calling the function foo is the same as calling the __call__ attribute of foo. However, the last three lines seem to indicate that they are different beasts since I changed the __call__ attribute but it didn't change the value returned by a call to foo().

Can someone explain the relationship between calling foo() and calling foo.__call__()? Is there a way to modify the behavior of the function so that foo() as well as foo.__call__() now returns 6 instead of 5?

like image 503
Zoot101 Avatar asked Mar 14 '12 18:03

Zoot101


People also ask

What is __ call __ function 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 __ function in Python?

The underscore _ is special in Python. While the underscore is used for just snake-case variables and functions in many languages, but it has special meanings in Python. They are used extensively in various scenarios including cases where we'd like to ignore some value, or in declaration of variables, methods etc.

What is __ class __ in Python?

__class__ is an attribute on the object that refers to the class from which the object was created. a. __class__ # Output: <class 'int'> b. __class__ # Output: <class 'float'> After simple data types, let's now understand the type function and __class__ attribute with the help of a user-defined class, Human .


1 Answers

I recommend you read special method lookup for new-style classes (especially the last paragraph).

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.

like image 50
gcbirzan Avatar answered Sep 26 '22 20:09

gcbirzan