使用__str__表示形式在Python容器中打印对象 [英] Using __str__ representation for printing objects in containers in Python

查看:121
本文介绍了使用__str__表示形式在Python容器中打印对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到,当将具有重载的__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容器中打印对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆