I159
I159

Reputation: 31189

How to use __call__?

For example, I need for class calling returns string.

class Foo(object):
    def __init__(self):
        self.bar = 'bar'

    def __call__(self):
        return self.bar

Foo calling returns Foo object.

Foo()
<__main__.Foo object at 0x8ff6a8c>

What should I do to class returns string or other? How to use __call__?

Upvotes: 3

Views: 377

Answers (3)

Karl Knechtel
Karl Knechtel

Reputation: 61607

In Python, everything is an object. Even classes.

Classes, furthermore, are callable objects. You don't have to do anything to make this happen, they just are. Calling the class creates an instance.

Setting up a __call__ method makes the instances also callable. You call the instances the same way you called the class (or any other function).

Upvotes: 5

avasal
avasal

Reputation: 14864

In [1]: class A:
   ...:     def __init__(self):
   ...:         print "init"
   ...:         
   ...:     def __call__(self):
   ...:         print "call"
   ...:         
   ...:         

In [2]: a = A()
init

In [3]: a()
call

Upvotes: 4

glglgl
glglgl

Reputation: 91099

With your example (of limited usefulness), you have a class of callable objects.

You can do now, as you have done,

>>> o = Foo()
>>> o
<__main__.Foo object at 0x8ff6a8c>
>>> o()
'bar'

I. e., __call__() does not make your class callable (as it is already), but it gives you a callable object.

Upvotes: 8

Related Questions