__zvanīt__ programmā Python

Python ir iebūvēts metožu kopums un __call__> ir viens no tiem. The __call__> metode ļauj Python programmētājiem rakstīt klases, kurās gadījumi darbojas kā funkcijas un tos var izsaukt kā funkciju. Kad gadījums tiek izsaukts kā funkcija; ja šī metode ir definēta, x(arg1, arg2, ...)> ir saīsinājums vārdam x.__call__(arg1, arg2, ...)> .

object() is shorthand for object.__call__() 

1. piemērs:




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

Izvade:

 Instance Created Instance is called via special method 

2. piemērs:




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

Izvade:

 Instance Created 200