How do I change the string representation of a Python class? [duplicate]

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

2 Answers
2

Leave a Comment