logo

__call__ w Pythonie

Python ma zestaw wbudowanych metod i__call__>jest jednym z nich. The__call__>Metoda umożliwia programistom Pythona pisanie klas, których instancje zachowują się jak funkcje i można je wywoływać jak funkcję. Gdy instancja jest wywoływana jako funkcja; jeśli ta metoda jest zdefiniowana,x(arg1, arg2, ...)>jest skrótem odx.__call__(arg1, arg2, ...)>.

object() is shorthand for object.__call__()>

Przykład 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()>



>

para C++
>

Wyjście :

 Instance Created Instance is called via special method>

Przykład 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>)>

>

>

Wyjście :

 Instance Created 200>