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 で、y軸に二種類の軸を設定する方法

y軸に、2種類のグラフを異なるスケールでプロットする。 matplotlib axes の twinx() を使う。 https://matplotlib.org/stable/api/_as_gen …

no image

matplotlib で、グラフの点の見た目を変更する方法

「marker」で指定すればよい。 次のページを参考に、plotの「marker」を変更する。 https://matplotlib.org/stable/api/markers_api.html 例 …

no image

matplotlib で、縦横の線(グリッド)を描く方法

pyplot grid で縦横線(罫線のようなもの)を引くことができる。 例 from matplotlib import pyplot as plt data_x = [25,26,27] …

no image

matplotlib で、線の種類を変更する方法

「linestyle = 」として、線の種類を指定することができる設定の詳細は、次のリンクを参照。 https://matplotlib.org/stable/gallery/lines_bars_a …

no image

matplotlib でグラフの中に注釈の文字を書く方法

annotate を使う。 例 import numpy as np from matplotlib import pyplot as plt x = np.linspace(-10,10,100) …