__str__() in python – what and why it is used?

What is the use of __str__() in python?

This is very similar to the toString() method in Java for an object. Thus if you override the __str__ method inside a class definition in Python, you get the see the friendly name of the object.

Let me show you an example code

Initially we had the Person class with nothing implemented. It just had a bare skeleton of a class.
We tried creating a object from the class Person and printed out the same. It showed a Person instance at some memory reference.

Next we again redefined the class overriding the __str__ method and when printed out the object reference it displayed the string which was returned from the __str__ method.

Hope it helps.

Leave a Reply

Your email address will not be published. Required fields are marked *