__str__用于生成人类可读的字符串,适合展示给用户;__repr__则生成明确无歧义的开发者用字符串,理想情况下可重构对象。两者分工明确,建议优先定义__repr__以保障调试信息完整,再根据需要定义__str__提供友好显示。若只选其一,应优先实现__repr__。

在Python里,
__str__
__repr__
__str__
__repr__
理解
__str__
__repr__
__str__
当你调用
print()
str()
__str__
立即学习“Python免费学习笔记(深入)”;
如果一个类没有定义
__str__
__repr__
str()
__repr__
<__main__.MyObject object at 0x...>
__repr__
而
__repr__
repr()
__repr__
如果一个类既没有定义
__str__
__repr__
str()
repr()
<模块.类名 object at 内存地址>
让我们看一个简单的例子:
class MyPoint:
    def __init__(self, x, y):
        self.x = x
        self.y = y
    def __str__(self):
        # 给人看的,更简洁、友好
        return f"坐标点: ({self.x}, {self.y})"
    def __repr__(self):
        # 给开发者看的,更明确,理想情况能重构对象
        return f"MyPoint(x={self.x}, y={self.y})"
p = MyPoint(10, 20)
print(p)         # 调用 __str__
# 输出: 坐标点: (10, 20)
print(str(p))    # 调用 __str__
# 输出: 坐标点: (10, 20)
print(repr(p))   # 调用 __repr__
# 输出: MyPoint(x=10, y=20)
# 在交互式解释器中直接输入 p 会调用 __repr__
# >>> p
# MyPoint(x=10, y=20)通过这个例子,我们能很直观地看到它们的不同输出风格和背后的设计意图。
这背后其实有个挺有意思的设计理念,我个人觉得它体现了Python在“易用性”和“严谨性”之间的平衡。设想一下,如果只有一个
toString()
Python选择将这个责任拆分开来,就是为了满足不同的使用场景。
__str__
而
__repr__
MyObject(id=123, status='active', created_at='2023-10-26')
__str__
__repr__
这是一个非常实际的问题,我的经验是,遵循一些最佳实践可以避免很多困惑。
首先,几乎总是应该定义__repr__
__repr__
__repr__
eval()
其次,只有当__str__
__repr__
__str__
__repr__
__str__
__str__
str()
__repr__
举个例子:
__repr__
Point(x=1, y=2)
__str__
str()
__repr__
__repr__
User(id=123, username='alice', email='alice@example.com', status='active')
__str__
用户: alice (ID: 123)
所以,我的建议是,先写好
__repr__
__str__
只定义其中一个,确实会带来一些后果,理解这些能帮助我们更好地设计类。
如果只定义了__str__
__repr__
repr()
<__main__.MyObject object at 0x7f8d4c0b7d00>
print()
__str__
class OnlyStr:
    def __init__(self, name):
        self.name = name
    def __str__(self):
        return f"我的名字是 {self.name}"
obj_str = OnlyStr("张三")
print(obj_str)      # 我的名字是 张三
print(repr(obj_str)) # <__main__.OnlyStr object at 0x...> (默认的repr,无用)如果只定义了__repr__
__str__
__str__
str()
print()
__repr__
__repr__
print()
class OnlyRepr:
    def __init__(self, value):
        self.value = value
    def __repr__(self):
        return f"OnlyRepr(value={self.value})"
obj_repr = OnlyRepr(123)
print(obj_repr)      # OnlyRepr(value=123) (因为没有__str__,所以print调用了__repr__)
print(repr(obj_repr)) # OnlyRepr(value=123)所以,总结一下,如果你只能选择定义一个,那么定义__repr__
__str__
__repr__
                        
                        python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
                Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号