← 中文资源

简体中文版本

repr 与 str 面向不同的读者

__repr__ 面向开发者给出无歧义、可重构的形式,__str__ 面向最终读者;容器渲染元素只用 repr,缺少任一方法时的回退路径也不同。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

(3, 4)
Point(3, 4)
(3, 4)
[Point(3, 4), Point(3, 4)]
True
repr falls back to default: True

实现说明

活动部件是类 Point、OnlyRepr、OnlyStr和函数 __init__、__repr__、__str__。

使用要点

  • 演示输出是带标签的(repr falls back to default:),每个操作都会留下自己的一行标注。

常见问题

有第三方依赖吗?

没有。依赖清单是空的,代码只用标准库。 文件在加载时定义 __init__、__repr__、__str__。

签名一览:def __init__(self, x, y)

核心语句

def __init__(self, x, y):
    self.x, self.y = x, y
def __repr__(self):
    return f"Point({self.x}, {self.y})"
def __repr__(self):
    return "repr form"

代码示例

class Point:
    def __init__(self, x, y):
        self.x, self.y = x, y

    # __repr__ targets developers: unambiguous, ideally re-constructible
    def __repr__(self):
        return f"Point({self.x}, {self.y})"

    # __str__ targets end users: readable, even if it loses information
    def __str__(self):
        return f"({self.x}, {self.y})"

point = Point(3, 4)
print(str(point))
print(repr(point))
print(point)  # print uses __str__ when available

# Containers render their items with repr only — __str__ never runs there
print([point, point])

# str() falls back to __repr__ when __str__ is missing
class OnlyRepr:
    def __repr__(self):
        return "repr form"

print(str(OnlyRepr()) == "repr form")

# With only __str__, repr() uses the default object repr, not your string
class OnlyStr:
    def __str__(self):
        return "str form"

print("repr falls back to default:", "OnlyStr object" in repr(OnlyStr()))