the __call__
dunder method of a class is supposed to represent the operator ()
, correct?
if so, why the following code is not working as expected?
def f():
print("hello world")
f()
>>>hello world
f.__call__ = lambda: print("foo") #replace the call operator
f()
>>>hello world
f.__call__()
>>>foo
something special is happening with <class 'function'>
could someone shine a light on this problem?
CodePudding user response:
You have not changed the __call__
method of a class. You have changed the __call__
method of a class instance. That's the difference. You would need to change the __call__
method of the function class, which of course you don't really want to do.
The documentation on this is terse:
Class Instances
Instances of arbitrary classes can be made callable by defining
a __call__() method in their class.
It specifically says "in their class", and not "in the instance". This is just a design decision on Python's part. You can imagine how confusing it would be if different instances of a class behaved differently in that case.