Skip to content Skip to sidebar Skip to footer

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 call

Solution 1:

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.

Solution 2:

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).

Solution 3:

In [1]: classA:
   ...:     def__init__(self):
   ...:         print"init"
   ...:         
   ...:     def__call__(self):
   ...:         print"call"
   ...:         
   ...:         

In [2]: a = A()
init

In [3]: a()
call

Post a Comment for "How To Use __call__?"