问题描述
我注意到,当将具有重载的__str__
方法的实例作为参数传递给print
函数时,它将按预期打印.但是,将包含这些实例之一的容器传递给print
时,它将改为使用__repr__
方法.也就是说,print(x)
显示x
的正确字符串表示形式,并且print(x, y)
可以正常工作,但是print([x])
或print((x, y))
会打印__repr__
表示形式.
I've noticed that when an instance with an overloaded __str__
method is passed to the print
function as an argument, it prints as intended. However, when passing a container that contains one of those instances to print
, it uses the __repr__
method instead. That is to say, print(x)
displays the correct string representation of x
, and print(x, y)
works correctly, but print([x])
or print((x, y))
prints the __repr__
representation instead.
首先,为什么会这样?其次,在这种情况下是否有办法纠正print
的行为?
First off, why does this happen? Secondly, is there a way to correct that behavior of print
in this circumstance?
推荐答案
使用对象的__str__
的容器的问题将是总的歧义-如果print L
显示? L
可以是['1, 2']
(单个项目列表,其字符串项目包含逗号)或四个2项目列表中的任何一个(因为每个项目可以是字符串或整数).类型的歧义对于print
是很常见的,但是项目的总歧义(因为每个逗号可以分隔字符串项目的或部分)是决定性的考虑.
The problem with the container using the objects' __str__
would be the total ambiguity -- what would it mean, say, if print L
showed [1, 2]
? L
could be ['1, 2']
(a single item list whose string item contains a comma) or any of four 2-item lists (since each item can be a string or int). The ambiguity of type is common for print
of course, but the total ambiguity for number of items (since each comma could be delimiting items or part of a string item) was the decisive consideration.
这篇关于使用__str__表示形式在Python容器中打印对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!