ZetCode

Python repr 函数

上次修改时间:2025 年 4 月 11 日

本全面指南探讨 Python 的 repr 函数,该函数返回对象的字符串表示形式。我们将涵盖基本用法、自定义对象以及创建明确对象表示形式的实用示例。

基本定义

repr 函数返回一个包含对象可打印表示形式的字符串。它的目的是明确无误,并且通常看起来像有效的 Python 代码,可以重新创建该对象。

主要特点:用于调试,通常返回有效的 Python 代码,在容器中打印对象时由 Python 使用,并调用对象的 __repr__ 方法。

基本用法与内置类型

以下是与不同内置类型的简单用法,显示了 repr 如何创建常见 Python 对象的字符串表示形式。

basic_repr.py
# With numbers
print(repr(42))       # '42'
print(repr(3.14))      # '3.14'

# With strings
print(repr('hello'))   # "'hello'"
print(repr("world"))   # '"world"'

# With containers
print(repr([1, 2, 3])) # '[1, 2, 3]'
print(repr({'a': 1}))  # "{'a': 1}"

此示例显示了 repr 与不同内置类型的使用。对于数字,它将数字作为字符串返回。对于字符串,它会添加引号。

字符串表示形式包括引号本身,使其清楚地表明它是一个字符串。对于容器,它显示了重新创建它们的完整语法。

repr 和 str 之间的区别

此示例演示了对象的 reprstr 表示形式之间的主要区别。

repr_vs_str.py
import datetime

now = datetime.datetime.now()

print(str(now))   # '2025-04-11 14:30:15.123456'
print(repr(now))  # 'datetime.datetime(2025, 4, 11, 14, 30, 15, 123456)'

class Example:
    def __str__(self):
        return "User-friendly string"
    
    def __repr__(self):
        return "Example()"

e = Example()
print(str(e))   # 'User-friendly string'
print(repr(e))  # 'Example()'

datetime 示例显示 str 提供了一种可读的格式,而 repr 显示了如何重新创建对象。自定义类显示了相同的区别。

repr 专为开发人员设计,而 str 专为最终用户设计。 打印容器时,Python 对元素使用 repr

带有 __repr__ 的自定义对象

您可以通过实现 __repr__ 特殊方法来使自定义对象与 repr 正确配合使用。

custom_repr.py
class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y
    
    def __repr__(self):
        return f"Point({self.x}, {self.y})"
    
    def __str__(self):
        return f"({self.x}, {self.y})"

p = Point(3, 4)
print(repr(p))  # 'Point(3, 4)'
print(str(p))   # '(3, 4)'
print([p])      # [Point(3, 4)]

Point 类同时实现了 __repr____str__repr 显示了如何重新创建对象,而 str 显示了一个简化的版本。

当点位于列表中时,Python 使用 repr 来表示它,这证明了为什么 __repr__ 很重要。

使用 repr 调试

此示例显示了 repr 如何通过提供更详细的对象信息来用于调试。

debugging.py
data = {
    'name': 'Alice',
    'age': 30,
    'scores': [95, 88, 92],
    'active': True
}

print("Debug output:")
print(repr(data))

# Output shows the complete structure with types:
# {'name': 'Alice', 'age': 30, 'scores': [95, 88, 92], 'active': True}

user_input = "Hello\nWorld"
print("User input representation:")
print(repr(user_input))  # Shows the newline character: 'Hello\nWorld'

字典示例显示了 repr 如何显示完整的结构,其中所有类型都可见。 这对于调试非常宝贵。

字符串示例演示了 repr 如何使特殊字符可见,这与常规打印不同,后者将显示实际的换行符。

错误处理

虽然 repr 通常适用于所有对象,但此示例显示了边缘情况以及如何处理它们。

errors.py
class BadRepr:
    def __repr__(self):
        raise Exception("Broken repr")

try:
    print(repr(BadRepr()))
except Exception as e:
    print(f"Error in repr: {e}")

# Default repr behavior
class NoRepr:
    pass

print(repr(NoRepr()))  # Shows default object representation

第一个示例显示了当 __repr__ 引发异常时会发生什么。 第二个示例显示了未定义 __repr__ 时的默认表示形式。

默认表示形式包括类名和内存地址,这总比没有好,但不如自定义实现有用。

最佳实践

资料来源

作者

我的名字是 Jan Bodnar,我是一位充满激情的程序员,拥有丰富的编程经验。 我从 2007 年开始撰写编程文章。 迄今为止,我撰写了超过 1,400 篇文章和 8 本电子书。 我拥有超过十年的编程教学经验。

列出所有 Python 教程