Python の __call__
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:
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