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

python3 で、リストを pop したものの返り値

リストを pop すると、 pop された値が返される。 例 plant_1 = [’pumpkin’, ‘ginger’, ‘potato’] plant_2 = [] print( …

no image

python3 でファイルに内容を追記する方法

ファイルを開くとき、「a+」を指定することで、data.txt というファイルを書き込みモードで開く。(もしファイルが存在していなければ作成する。) 例 f = open(‘data.txt’, ‘a …

no image

matplotlib で複数のグラフを並べて表示する方法

plot.subplots() でグラフの縦方向と横方向の数を指定する。 例 import numpy as np from matplotlib import pyplot as plt x1 = …

no image

python3 でリストを結合する方法

2つのリストを結合して、「リストのリストを作りたい場合」と、「1つの長いリストを作りたい」場合がある。 それぞれ、次のようにする。 例 # リスト2つを用意 l_1 = [1,2,3] l_2 …

no image

matplotlib で、縦横の罫線を引く方法

破線をカスタマイズする方法 以下では、dashes = [5,2,2,2] で、線5・空白2・線2・空白2の破線を指定している。 詳しくは次を参照。 https://matplotlib.org/st …