作用
编写类自定义 repr() 和 str() 通常是很好的习惯,它能简化调试和实例输出,程序员会看到实例更加详细与有用的信息。类中如果 str() 没有定义,就会使用 repr() 来代替输出。
区别
repr() => 阅读友好
str() => 解释器友好
通常,__repr__()
生成的文本最好能让 eval()
执行。
class Pair:
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return 'Pair({0.x!r}, {0.y!r})'.format(self) # 0.x 相当于 self.x
def __str__(self):
return '({0.x!s}, {0.y!s})'.format(self)
p = Pair(1, 2)
print(type(eval(p.__repr__()))) # <class '__main__.Pair'>
print(p.__repr__()) # Pair(1, 2)
print(type(p.__str__())) # <class 'str'>
print(p.__str__()) # (1, 2)