Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
106
Help us understand the problem. What is going on with this article?

More than 5 years have passed since last update.

@ko-da-k

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

クラスを作るときに、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__に返り値をつければ,インスタンスから得られた値を別の変数に使ったりもできるということ。

106
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
106
Help us understand the problem. What is going on with this article?