Python repr() 関数
repr()これは、Pythonでオブジェクトの印刷可能な表現を取得するための組み込み関数です。
repr()オブジェクトの公式な文字列表現を返し、通常はそのオブジェクトを再作成するために使用できます。これはstr()との違いは、repr()よりデバッグと開発に重点を置いており、一方str()ユーザーフレンドリーに重点を置いています。
単語の説明: reprであるrepresentation(表示)の略です。
基本構文とパラメータ
構文形式
repr(object)
パラメータの説明
- パラメータ object:
- 型:任意のオブジェクト
- 説明:文字列表現を取得するオブジェクト。
関数の説明
- 戻り値:文字列を返します。通常はそのオブジェクトを表す文字列です。
- 特殊メソッド:オブジェクトは
__repr__メソッドを定義することで戻り値をカスタマイズできます。
例
例1:repr() 対 str()
例
# 文字列の違い
s = "hello"
print(f"str: '{str(s)}'") # 出力: str: 'hello'
print(f"repr: '{repr(s)}'") # 出力: repr: 'hello'
# 日時の違い
from datetime import datetime
dt = datetime.now()
print(f"str: {str(dt)}")
print(f"repr: {repr(dt)}")
# カスタムクラスの違い
class Person:
def __init__(self, name):
self.name = name
def __str__(self):
return f"Person: {self.name}"
def __repr__(self):
return f"Person(name='{self.name}')"
p = Person("Tom")
print(f"str: {str(p)}")
print(f"repr: {repr(p)}")
s = "hello"
print(f"str: '{str(s)}'") # 出力: str: 'hello'
print(f"repr: '{repr(s)}'") # 出力: repr: 'hello'
# 日時の違い
from datetime import datetime
dt = datetime.now()
print(f"str: {str(dt)}")
print(f"repr: {repr(dt)}")
# カスタムクラスの違い
class Person:
def __init__(self, name):
self.name = name
def __str__(self):
return f"Person: {self.name}"
def __repr__(self):
return f"Person(name='{self.name}')"
p = Person("Tom")
print(f"str: {str(p)}")
print(f"repr: {repr(p)}")
期待される実行結果:
str: 'hello' repr: 'hello' str: 2024-01-15 10:30:45.123456 repr: datetime.datetime(2024, 1, 15, 10, 30, 45, 123456) str: Person: Tom repr: Person(name='Tom')
コードの解説:
- 単純な文字列の場合、両者の結果は同じです。
- 日時の場合、
repr()オブジェクトを再構築できる式を返します。 - カスタムクラスはそれぞれ
__str__と__repr__メソッドを定義できます。
例2:repr() を使ったデバッグ
例
# 隠し文字を表示
s = "hello\nworld"
print(f"str: {str(s)}")
print(f"repr: {repr(s)}")
# 引用符を表示
text = "She said 'hello'"
print(f"str: {str(text)}")
print(f"repr: {repr(text)}")
# 対話環境で
# 変数名を直接入力すると repr() が呼び出されます
s = "hello\nworld"
print(f"str: {str(s)}")
print(f"repr: {repr(s)}")
# 引用符を表示
text = "She said 'hello'"
print(f"str: {str(text)}")
print(f"repr: {repr(text)}")
# 対話環境で
# 変数名を直接入力すると repr() が呼び出されます
期待される実行結果:
str: hello world repr: 'hello\nworld' str: She said 'hello' repr: "She said 'hello'"
repr()隠し文字(改行文字など)や引用符を表示できるため、デバッグに便利です。
その他の拡張
Python3 組み込み関数