猫型エンジニアのブログ

プログラム/ネットワーク系の技術関連をまとめたページです 

__call__メソッドについて

 __call__()メソッドを定義した場合、関数が呼び出せるのと同じようにクラスのインスタンスを呼び出せるようになります。

__call__()メソッド定義時

>>> class Test(object):
...     def __init__(self):
...         print "__init__"
...     def __call__(self):
...         print "__call__"
... 
>>> test = Test()
__init__
>>> test()
__call__

__call__()メソッド非定義時

>>> class Test(object):
...     def __init__(self):
...         print "__init__"
... 
>>> test = Test()
__init__
>>> test()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'Test' object is not callable