Reputation: 191
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?
Upvotes: 12
Views: 1794
Reputation: 1514
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.
Upvotes: 12