Python には一連の組み込みメソッドがあり、__call__>もその1つです。の__call__>このメソッドを使用すると、Python プログラマーは、インスタンスが関数のように動作し、関数のように呼び出すことができるクラスを作成できます。インスタンスが関数として呼び出される場合。このメソッドが定義されている場合、x(arg1, arg2, ...)>の略記ですx.__call__(arg1, arg2, ...)>。
object() is shorthand for object.__call__()>
例 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()> |
>
>
おっと
出力:
Instance Created Instance is called via special method>
例 2:
ピーナッツ vs 落花生
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>)> |
ピート・デビッドソンの年齢
>
>
出力:
Instance Created 200>