__skambinti__ Python

Python turi integruotų metodų rinkinį ir __call__> yra vienas iš jų. The __call__> metodas leidžia Python programuotojams rašyti klases, kuriose egzemplioriai elgiasi kaip funkcijos ir gali būti vadinami kaip funkcija. Kai egzempliorius iškviečiamas kaip funkcija; jei šis metodas yra apibrėžtas, x(arg1, arg2, ...)> yra trumpinys x.__call__(arg1, arg2, ...)> .

object() is shorthand for object.__call__() 

1 pavyzdys:




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

Išvestis:

 Instance Created Instance is called via special method 

2 pavyzdys:




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

Išvestis:

 Instance Created 200