Python - Call Expressions: __call__

Introduction

The __call__ method is called when your instance is called.

Python runs a __call__ method for function call expressions applied to your instances.

This allows instances to conform to a function-based API:

Demo

class Callee: 
    def __call__(self, *pargs, **kargs):       # Intercept instance calls 
        print('Called:', pargs, kargs)         # Accept arbitrary arguments 
# from  w  w  w  . j a v  a2  s  . c o m
C = Callee() 
C(1, 2, 3)                                     # C is a callable object 
C(1, 2, 3, x=4, y=5) 

X = C() 
X(1, 2)                                            # Omit defaults 
X(1, 2, 3, 4)                                      # Positionals 
X(a=1, b=2, d=4)                                   # Keywords 
X(*[1, 2], **dict(c=3, d=4))                       # Unpack arbitrary arguments 
X(1, *(2,), c=3, **dict(d=4))                      # Mixed modes

Result