__chiama__ in Python

Python ha una serie di metodi integrati e __call__> è uno di questi. IL __call__> Il metodo consente ai programmatori Python di scrivere classi in cui le istanze si comportano come funzioni e possono essere chiamate come una funzione. Quando l'istanza viene chiamata come funzione; se questo metodo è definito, x(arg1, arg2, ...)> è una scorciatoia per x.__call__(arg1, arg2, ...)> .

object() is shorthand for object.__call__() 

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

Produzione :

 Instance Created Instance is called via special method 

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

Produzione :

 Instance Created 200