0
0

Static Method / Instance Method として呼び出されたときの挙動を変える

Posted at

どうすれば良いか

self に初期値を設定してあげると、インスタンス関数をクラスから呼び出したときもエラーが出なくなる。

.py
from typing import Self


class A():
    def A(self: Self | None = None):
        if self is None:
            print("I am static method A")
        else:
            print("I am instance method A")


A.A()
# >>> I am static method A

A().A()
# >>> I am instance method A

便利だと思うか、分かりにくいと思うかはあなた次第。

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