Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using __str__ representation for printing objects in containers

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.

First off, why does this happen? Secondly, is there a way to correct that behavior of print in this circumstance?

like image 628
BobDobbs Avatar asked Apr 14 '10 02:04

BobDobbs


People also ask

What is the __ str __ method used for?

Python __str__() This method returns the string representation of the object. This method is called when print() or str() function is invoked on an object.

Does print use repr or str?

The print statement and str() built-in function uses __str__ to display the string representation of the object while the repr() built-in function uses __repr__ to display the object.

What is the purpose of defining the functions __ str __ and __ repr __ within a class how are the two functions different?

__str__ is used in to show a string representation of your object to be read easily by others. __repr__ is used to show a string representation of the object.

How do you print the value of a object in Python?

Use Python's vars() to Print an Object's Attributes The dir() function, as shown above, prints all of the attributes of a Python object. Let's say you only wanted to print the object's instance attributes as well as their values, we can use the vars() function.


1 Answers

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.

like image 139
Alex Martelli Avatar answered Oct 04 '22 20:10

Alex Martelli