0
0

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 マジックメソッド一覧

Last updated at Posted at 2025-10-18

pythonの初心者です。

pythonのインスタンスには
javaのtoString(文字列表現を取得)
phpの__invoke(インスタンスそのものを「実行」)

のように暗黙的に宣言するメソッドが多いなと思ったので備忘投稿です。

そもそもpythonの場合はマジックメソッドではなく組み込みメソッドって呼ぶんですかね

Tax.py
import re

class Tax:
    rate = 0.1

# このクラスのインスタンスのデフォルトの挙動は現在の消費税率の表示とする
    def __call__(self):
        rate = self.rate * 10

        print(f'現在の消費税率{rate}%')
    
    def setRate(self, rate):
        if (not re.search("^[0-9].[0-9]", str(rate))):
            raise Exception('税率は小数で指定してください。')
        self.rate = rate

    def calcurate(self, prize):
        return prize + prize * self.rate
from Tax import Tax
tax = Tax()
tax()   // 現在の消費税率10.0%
tax.setRate(0.2)
tax()  // 現在の消費税率20.0%

tax()のようにインスタンス変数自体を括弧をつけて関数を呼び出した場合に、__call__メソッド
がその名の通りコールされていることがわかる。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?