How to Override toString() in Python
In popular object-oriented languages such as Java and C#, they have a built-in method to each class that allows you to obtain a String representation of that class. They call these methods toString() or ToString(), respectively. You can use the default implementation, which basically gives you the name of the class (not usually very helpful). Or you can override the default by implementing this method in the class you are working with.
Python has a similar thing, except the name is pretty different. The method you must override is called __repr__.
Let’s say you have a simple class with a single method.
class TestClass: def Method1(self): return "method 1"
If you wanted to print the (default) String representation, you would do this:
print TestClass()
This gives you “<__main__.TestClass instance at 0×00A86580>.”
Then you can customize the String representation like this:
class TestClass: def Method1(self): return "method 1" def __repr__(self): return "here's the custom String representation"
Then when you do this:
print TestClass()
You get this: “here’s the custom String representation”
This functionality can come in very handy if you need to output the contents of objects to a file or the screen and you want to encapsulate the logic within the class itself rather than some other class.
This is correct in general, but __repr__ is not used for showing simple string representation of an object. It is used to give a more detailed string representation. Mostly, __str__ is overwritten.
Note that str() will call __str__ and repr() will call __repr__, but if only __repr__ is overwritten and not __str__, str() will call __repr__, too.