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

snakile picture snakile · Feb 6, 2011 · Viewed 157.9k times · Source

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

Answer

Mark Byers picture Mark Byers · Feb 6, 2011

The closest equivalent to Java's toString is to implement __str__ for your class. Put this in your class definition:

def __str__(self):
     return "foo"

You may also want to implement __repr__ to aid in debugging.

See here for more information: