__call__ v Pythonu

Python má sadu vestavěných metod a __call__> je jedním z nich. The __call__> metoda umožňuje programátorům Pythonu psát třídy, kde se instance chovají jako funkce a mohou být volány jako funkce. Když je instance volána jako funkce; pokud je tato metoda definována, x(arg1, arg2, ...)> je zkratka pro x.__call__(arg1, arg2, ...)> .

object() is shorthand for object.__call__() 

Příklad 1:




class> Example:> > def> __init__(> self> ):> > print> (> 'Instance Created'> )> > > # Defining __call__ method> > def> __call__(> self> ):> > print> (> 'Instance is called via special method'> )> > # Instance created> e> => Example()> > # __call__ method will be called> e()>

Výstup :

 Instance Created Instance is called via special method 

Příklad 2:




class> Product:> > def> __init__(> self> ):> > print> (> 'Instance Created'> )> > > # Defining __call__ method> > def> __call__(> self> , a, b):> > print> (a> *> b)> > # Instance created> ans> => Product()> > # __call__ method will be called> ans(> 10> ,> 20> )>

Výstup :

 Instance Created 200