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 で、配列の配列をソートする

ラムダ式を使って、任意の要素についてソートすることができる。 例 arr = [[1,2,3],[2,1,2],[3,3,4],[4,4,1]] for i i …

no image

python3 で辞書(dictionary)の一部を del で削除する

辞書の一部を削除するには、del で消去したいキーを指定する。 例 dict1 = {“名前”:”太郎”, “年齢”: 20, “住所”: “東京都千代田区大手町1-1”} print(dict1) …

no image

python3 で、すべて小文字かどうかを判定する方法

islower() 関数を使う。 例 print(‘abcde’.islower()) print(‘abcDe’.islower()) 結果 True False

no image

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

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

no image

python3 で辞書からランダムに要素を選択する方法

items() で辞書から要素を取り出し、random.choice でランダムに要素を選択する。 例 import random # 県庁所在地 mydict = {‘宮城県’:’仙台市’,’茨城県 …