0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Pythonの__call__って何?

Posted at

下記プログラムを実行して挙動を確認した

class test:
    def __init__(self, x, y):
        print("run __init__")
        self.x = x
        self.y = y
        self.print()
    
    def __call__(self, c):
        print("run __call__")
        self.x = self.x * c
        self.y = self.y * c
        self.print()
    
    def update(self, c):
        print("run update()")
        self.x = self.x * c
        self.y = self.y * c
        self.print()
    
    def print(self):
        print(f"x = {self.x}")
        print(f"y = {self.y}")

x = 2
y = 3
c1 = 3
c2 = 4
t = test(x, y)
t(c1)
t.update(c2)
t.update(c1)
t(c2)

下記はプログラムの実行結果。

run __init__
x = 2
y = 3
run __call__
x = 6
y = 9
run update()
x = 24
y = 36
run update()
x = 72
y = 108
run __call__
x = 288
y = 432

上記実験から、分かったこと。

  • __call__は、作成済みのインスタンスを呼び出したときに実行される。
  • __init__は、インスタンスの作成時に実行される。

感想

  • __call__は、作成済みのインスタンス名に()を付けると実行できるが、直観的でないと感じた
    • 用途にもよるだろうが、実現したい処理があるなら、分かりやすいメソッド名を付けたメソッドを作成して、そっちを使ったほうが可読性が上がりそう。__call__ではないと困るケースがあれば、詳しい方、教えてください。
0
1
0

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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?