为什么需要将对象转为字符串?
在 Python 中,对象默认没有直观的文本表示。当我们打印对象、记录日志或调试程序时,通常希望看到有意义的信息,而不是类似 <__main__.Person object at 0x...> 的内存地址。
Python 提供了多种机制,让我们可以控制对象如何被转换为字符串。
1. 使用内置函数 str()
str(obj) 会调用对象的 __str__ 方法(如果存在),否则回退到 __repr__。
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"姓名:{self.name},年龄:{self.age}"
p = Person("张三", 25)
print(str(p)) # 输出:姓名:张三,年龄:25
print(p) # 等价于 print(str(p))
2. 使用内置函数 repr()
repr(obj) 用于“开发者友好”的表示,通常应返回可执行的 Python 表达式(理想情况下)。
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return f"Point({self.x}, {self.y})"
pt = Point(3, 4)
print(repr(pt)) # 输出:Point(3, 4)
# 可直接用于 eval()(谨慎使用)
new_pt = eval(repr(pt))
3. 同时定义 __str__ 和 __repr__
最佳实践:为类同时实现两个方法。
- __str__ 面向用户,简洁易读。
- __repr__ 面向开发者,准确且可重现。
class Book:
def __init__(self, title, author):
self.title = title
self.author = author
def __str__(self):
return f"《{self.title}》 by {self.author}"
def __repr__(self):
return f"Book(title='{self.title}', author='{self.author}')"
b = Book("Python编程", "李四")
print(str(b)) # 《Python编程》 by 李四
print(repr(b)) # Book(title='Python编程', author='李四')
4. 默认行为
如果没有定义 __str__ 或 __repr__,Python 会使用默认的对象表示:
class Empty: pass
e = Empty()
print(e) # 输出类似:<__main__.Empty object at 0x000001F4A8C2D3A0>
小贴士
- 在容器(如列表、字典)中打印对象时,Python 会使用
__repr__而非__str__。 - 交互式解释器中直接输入对象名并回车,也会调用
__repr__。 - 始终优先实现
__repr__;__str__是可选的增强。