__call__ v Pythonu

Python ima nabor vgrajenih metod in __call__> je eden izmed njih. The __call__> omogoča programerjem Pythona pisanje razredov, kjer se primerki obnašajo kot funkcije in jih je mogoče poklicati kot funkcijo. Ko je primerek poklican kot funkcija; če je ta metoda definirana, x(arg1, arg2, ...)> je okrajšava za x.__call__(arg1, arg2, ...)> .

object() is shorthand for object.__call__() 

Primer 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()>

Izhod:

 Instance Created Instance is called via special method 

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

Izhod:

 Instance Created 200