logo

__call__ în Python

Python are un set de metode încorporate și__call__>este unul dintre ei. The__call__>metoda permite programatorilor Python să scrie clase în care instanțele se comportă ca niște funcții și pot fi apelate ca o funcție. Când instanța este apelată ca funcție; dacă această metodă este definită,x(arg1, arg2, ...)>este o prescurtare pentrux.__call__(arg1, arg2, ...)>.

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

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

>

>

Ieșire:

 Instance Created Instance is called via special method>

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

în care an a fost inventat computerul
>

>

Ieșire:

 Instance Created 200>