ベスパリブ

プログラミングを主とした日記・備忘録です。ベスパ持ってないです。

クラスの特殊メソッド__str__()とは

「クラスオブジェクトを文字列で返すメソッド」です

class Hoge():
    title = "this is Hoge."

    def __str__(self):
        return self.title

# クラスオブジェクトを表示すると
print(Hoge())  # this is Hoge.

# インスタンスでもOK
hoge = Hoge()
print(hoge)  # this is Hoge.

文字列でない場合、エラーが発生します。

class Hoge():
    title = "this is Hoge."

    def __str__(self):
        return 1  # 数値にすると...

print(Hoge())
""" 以下のようなエラーになる
Traceback (most recent call last):
  File "Main.py", line 7, in <module>
    print(Hoge())
TypeError: __str__ returned non-string (type int)
"""