1

I have got the following piece of code:

class Callable:
    def __init__(self, func):
        self.__call__ = func

when I test it, I get the following result:

>>> square = Callable(lambda x: x**2)
>>> square(3)
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
TypeError: 'Callable' object is not callable
>>> square.__call__(3)
9
>>> 

furthermore, when I define a __call__ method in the Class definition, the object is callable, but the Classes __call__ is called although the objects __call__ is the one I passed to the __init__ Function:

class Callable:
    def __call__(self, x):
        return -x

    def __init__(self, func):
        self.__call__ = func

Now, when testing I get:

>>> square = Callable(lambda x: x**2)
>>> square(3)
-3
>>> square.__call__(3)
9
>>> 

In Python 2 this works as expected (x(args) calls x.__call__(args)). Why doesn't this work in Python 3.4? And how can you fix this?

ANSWER: I'm answering my own question after seeing why this behaves like this here.

An easy way to fix this, that doesn't affect a client is:

class Callable:
    def __call__(self, x):
        return self.__call__(x)

    def __init__(self, func):
        self.__call__ = func

when I use this I get (as expected):

>>> a = Callable(lambda x: x**2)
>>> a(3)
9
Community
  • 1
  • 1
0x539
  • 1,489
  • 1
  • 13
  • 30
  • 1
    In Python 2 to get the same behavior you need to inherit from `object`, otherwise the class will be an old-style class that allowed special methods on instances as well. – Ashwini Chaudhary Nov 06 '14 at 16:49

0 Answers0