为什么 python 的 __repr__ 的字典比它的 __str__ 更具可读性?

How come python's __repr__ of a dict is more readable than its __str__?

看下面的例子:

In [33]: test = {x:str(x)*10 for x in range(10)}

In [35]: print test
{0: '0000000000', 1: '1111111111', 2: '2222222222', 3: '3333333333', 4: '4444444444', 5: '5555555555', 6: '6666666666', 7: '7777777777', 8: '8888888888', 9: '9999999999'}

In [34]: test
Out[34]: 
{0: '0000000000',
 1: '1111111111',
 2: '2222222222',
 3: '3333333333',
 4: '4444444444',
 5: '5555555555',
 6: '6666666666',
 7: '7777777777',
 8: '8888888888',
 9: '9999999999'}

打印函数 (__str__) 的输出客观上比 __repr__ 输出的可读性差。这是一条长线,可以自动换行成多行,没有间距。它们都非常明确,可以让你用它们的输出重建对象。

相反的输出在这里是否有意义,__repr__ 是紧凑的表示,__str__ 具有更易读的换行符?

IPython 这样做,所以 print 做常规的事情,但只是命名变量做很酷的事情,这就是为什么...

print 打印 pandas dataframes 变得丑陋,只是命名变量就很漂亮

注意 :

"This will blow your mind: repr(test) == str(test)"

理所当然,非IPython口译员不会让这种情况发生。

这只是 ipython 的事情。在标准 Python 3.7 REPL 中,这是输出:

>>> test = {x:str(x)*10 for x in range(10)}
>>> print(test)
{0: '0000000000', 1: '1111111111', 2: '2222222222', 3: '3333333333', 4: '4444444444', 5: '5555555555', 6: '6666666666', 7: '7777777777', 8: '8888888888', 9: '9999999999'}
>>> test
{0: '0000000000', 1: '1111111111', 2: '2222222222', 3: '3333333333', 4: '4444444444', 5: '5555555555', 6: '6666666666', 7: '7777777777', 8: '8888888888', 9: '9999999999'}
>>>

如果我们将其作为 "normal" 脚本执行,输出是相同的:

test = {x: str(x) * 10 for x in range(10)}
print(str(test))
#  {0: '0000000000', 1: '1111111111', 2: '2222222222', 3: '3333333333', 4: '4444444444', 5: '5555555555', 6: '6666666666', 7: '7777777777', 8: '8888888888', 9: '9999999999'}
print(repr(test))
#  {0: '0000000000', 1: '1111111111', 2: '2222222222', 3: '3333333333', 4: '4444444444', 5: '5555555555', 6: '6666666666', 7: '7777777777', 8: '8888888888', 9: '9999999999'}

strrepr 表示中没有换行符,正如之前在评论中提到的那样:

print(repr(test) == str(test))
# True

结论是,这只是 ipython 主动让 repr 的输出更加人性化。