188
119

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Pythonのクラスにおける__call__メソッドの使い方

Last updated at Posted at 2016-03-20

クラスを作るときに、__init__は頻繁に使うけど、__call__って何ってなったときに自分なりに解釈

環境はPython 3.5.1 :: Anaconda 2.5.0 (x86_64)
実行は、Jupyter notebookにて

__call__は関数っぽく呼び出したら発動

クラス例

class_sample.py
class A:
    
    def __init__(self, a):
        self.a = a
        print("A init")
        
    def __call__(self, b):
        print("A call")
        print(b + self.a)
        
class B(A):
    
    def __init__(self, a, c):
        super().__init__(a)
        self.c = c
        print("B init")
    
    def __call__(self, d):
        print("B call")
        print(self.a + self.c + d)

実行例

>>> a = A(1)
A init

>>> a(2)
A call
3

>>> b = B(1,3)
A init
B init

>>> b(4)
B call
8

インスタンス生成では__init__しか呼び出されない。しかし、一度生成されたインスタンスを関数っぽく引数を与えて呼び出せば、__call__が呼び出されるという仕組み
もちろん、__call__に返り値をつければ,インスタンスから得られた値を別の変数に使ったりもできるということ。

188
119
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
188
119

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?