__call__ i Python
Python har en uppsättning inbyggda metoder och __call__> är en av dem. De __call__> metod gör det möjligt för Python-programmerare att skriva klasser där instanserna beter sig som funktioner och kan kallas som en funktion. När instansen anropas som en funktion; om denna metod är definierad, x(arg1, arg2, ...)> är en stenografi för x.__call__(arg1, arg2, ...)> .
object() is shorthand for object.__call__()
Exempel 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()> |
Utgång:
Instance Created Instance is called via special method
Exempel 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> )> |
Utgång:
Instance Created 200