Python の __repr__と__str__

レベル 4272 打鍵

__repr__と__str__で異なる文字列表現を示します。__repr__は開発者向け、__str__はエンドユーザー向けです。

Python のコード

# 2種類の文字列表現を持つBookクラスを定義します
1class Book:
# コンストラクタはタイトルと著者を受け取ります
2 def __init__(self, title, author):
# 2つの値をインスタンス属性として保存します
3 self.title = title
4 self.author = author
5
# __repr__は開発者向けの明確な表現で、repr()が使います
6 def __repr__(self):
# コンストラクタ呼び出しのような文字列を返します
7 return f"Book('{self.title}', '{self.author}')"
8
# __str__はユーザー向けの読みやすい表現で、str()やprint()が使います
9 def __str__(self):
# 「タイトル by 著者」の形で返します
10 return f"{self.title} by {self.author}"
11
# Bookのインスタンスを作成します
12b = Book("1984", "Orwell")
# repr(b)は__repr__を呼びます:Book('1984', 'Orwell')
13print(repr(b))
# str(b)は__str__を呼びます:1984 by Orwell
14print(str(b))

実行結果

Book('1984', 'Orwell')
1984 by Orwell
このコードでタイピング練習する

このコードでタイピング練習ができます。記録はランキングに反映されません。

このコードで使う記号

この Python のコードで打つ記号と、出てくる回数です。

  • _× 12
  • (× 9
  • )× 9
  • "× 8
  • .× 6
  • ,× 4
  • :× 4
  • '× 4
  • {× 4
  • }× 4

Python のレベル 4 のほかのコード例

← Python タイピング練習のトップへ