12

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?

Zoot101
  • 191
  • 7

1 Answers1

12

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.

Ngo Bao
  • 3
  • 2
gcbirzan
  • 1,494
  • 11
  • 17
  • 2
    You should elaborate about how the fact that we're working with a function here doesn't really matter, since functions are objects and there's a class that they belong to (``), etc.... – Karl Knechtel Mar 14 '12 at 20:44