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?
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.
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.
__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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With