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 でエラーバーを設定する方法

pyplot.errorbar を使って設定する。 オプションの詳細は https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.erro …

no image

python3 で文字列を入力させて受け取る方法

C言語で scanf のようなものを作るには、python では input() で実現できる。 例 print(‘xの値を入力してください’) x = input() print(‘xの値は ‘ + …

no image

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

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

no image

matplotlib で、グラフのタイトルに上付き文字を入力する方法

数学記号などで、グラフのタイトルに上付きの文字を入力したい場合がある。 その場合は次のように書いて設定できる。 例 import numpy as np from matplotlib import …

no image

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

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