python3

python の __str__ と __repr__ とは

投稿日:2020年12月16日 更新日:

python でクラスの情報を文字列で表示するとき、__str__ メソッドと __repr__ メソッドが使える。

__str__ は、プログラマーとは限らないユーザーに「読める形で情報を表示」することが目的である。

それに対し、__repr__ は、主にプログラマーがデバッグに使えるように、pythonの実行コードのような形の情報を出力することが目的である。

言い換えると、__str__ が readable (読みやすい)ことが目的なのに対し、__repr__ は unambiguous (曖昧でない)ことを目的にしている、という違いがある。

例(python3)

class Dog:
    def __init__(self):
        self.name = 'イヌ'
        self.age = 10
    def __repr__(self):
        return 'repr:' + self.name
    def __str__(self):
        return 'str:' + self.name

d = Dog()
print(str(d))    
print(repr(d))

結果

str:イヌ
repr:イヌ

-python3
-,

執筆者:


comment

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です

関連記事

no image

matplotlib で、凡例を表示する位置を変更する方法

凡例(legend)の表示位置を変更するには、axis の legend の loc を設定する。 次のリンクhttps://matplotlib.org/stable/api/_as_gen/mat …

no image

matplotlib で散布グラフを描く方法

pyplt.scatter を使って散布グラフを描くことができる。 点の色は、点ごとに変えることができる。 下の例では color の配列で点の色を指定している。 例 from matplotlib …

no image

matplotlib でcsv ファイルを読み込むとき、最初の行をスキップする方法

numpy の loadtxt で読み込む行を省略したい場合 スキップしたい行を # 等の記号でコメントアウトして、 loadtxt の comments = ‘#’ とすると …

no image

matplotlib で、グラフの線の幅を変更する方法

lw で、線幅を数字で指定すればよい。 例 from matplotlib import pyplot as plt data_x = [25,26,27] data_y = [39, …

no image

matplotlib で、軸に垂直・平行な線を書く方法

axhline, axvline を使ってx,y軸に平行な線を描くことができる。 https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot …