Python __str__ : How or when to use __str__ method

Python object (class instance) has __str__ method that returns the information of a object as string, which is almost meaningless by defualt.

class Animal:
    def __init__(self, name):
        self.name = name


a = Animal(name='fish')

print(a.__str__())  # <__main__.Animal object at 0x109c55e50>

But we can re-define __str__ as follows.

class Animal:
    def __init__(self, name):
        self.name = name

    def __str__(self):
        return 'I am ' + self.name + '.'


a = Animal(name='fish')

print(a.__str__())  # I am fish.

In Python, basically, __str__ is used to show the object representation or state. This method is called by __str__ or str. str is mainly used to convert object to string,

class Animal:
    def __init__(self, name):
        self.name = name

    def __str__(self):
        return 'I am ' + self.name + '.'


a = Animal(name='fish')

print(a.__str__())  # I am fish.
print(str(a))  # I am fish.

Python Class

Python Tutorial