__call__ v Pythone

Python má súbor vstavaných metód a __call__> je jedným z nich. The __call__> metóda umožňuje programátorom Pythonu písať triedy, kde sa inštancie správajú ako funkcie a možno ich volať ako funkcie. Keď sa inštancia volá ako funkcia; ak je táto metóda definovaná, x(arg1, arg2, ...)> je skratka pre x.__call__(arg1, arg2, ...)> .

object() is shorthand for object.__call__() 

Prí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ýkon :

 Instance Created Instance is called via special method 

Prí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ýkon :

 Instance Created 200