ThePhi
ThePhi

Reputation: 2621

Can __call__ return something in Python?

I'm trying to understand some program with inside a code like that:

class foo(object):
    def __init__(self):
        # some initializations 
        pass

    def __call__(self, a, b):
        return a+b

x = foo()
x(2, 3)

Is a return call inside __call__ an error? It doesn't raise any errors but how can we access the return value in __call__ then?

Upvotes: 0

Views: 3313

Answers (1)

Linuxios
Linuxios

Reputation: 35788

Yes, you absolutely can return a value from __call__, and the value will be used as the return value of the call itself.

Using your example:

class foo(object):
    def __init__(self):
        # some initializations 
        pass

    def __call__(self, a, b):
        return a+b

obj = foo()
print obj(1, 2) # Prints `3`

Upvotes: 7

Related Questions