In Java, I can override the toString() method of my class. Then Java’s print function prints the string representation of the object defined by its toString(). Is there a Python equivalent to Java’s toString()?
For example, I have a PlayCard class. I have an instance c of PlayCard. Now:
>>> print(c)
<__main__.Card object at 0x01FD5D30>
But what I want is something like:
>>> print(c)
A♣
How do I customize the string representation of my class instances?
I’m using Python 3.x
The closest equivalent to Java’s
toStringis to implement__str__for your class. Put this in your class definition:You may also want to implement
__repr__to aid in debugging.See here for more information: