__llamar__ en Python

Python tiene un conjunto de métodos integrados y __call__> es uno de ellos. El __call__> El método permite a los programadores de Python escribir clases donde las instancias se comportan como funciones y pueden llamarse como una función. Cuando la instancia se llama como una función; si este método está definido, x(arg1, arg2, ...)> es una abreviatura de x.__call__(arg1, arg2, ...)> .

object() is shorthand for object.__call__() 

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

Producción :

 Instance Created Instance is called via special method 

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

Producción :

 Instance Created 200