How to Override 'to string' Representation of a Class Object in Python
Python - Override 'to string' Representation of a Class Object
To override string representation of a class object in Python, define __str__(self) function and return the required string.
Example
Let us consider a class named Fruit as shown in the following without overriding __str__(self) function.
class Fruit:
    name = ''
    quantity = ''
    description = ''
    
    def __init__(self, name, quantity, description):
        self.name = name
        self.quantity = quantity
        self.description = descriptionIn the following example, we create an object of type Fruit, and print the object to console.
Python Program
class Fruit:
    name = ''
    quantity = ''
    description = ''
    
    def __init__(self, name, quantity, description):
        self.name = name
        self.quantity = quantity
        self.description = description
apple = Fruit('Apple', '58', 'Good for health.')
print(apple)Output
<__main__.Fruit object at 0x1025abc10>The string representation is difficult to read.
Now, we shall override the __str__(self) function and return a string that specifies the attributes in detail.
Python Program
class Fruit:
    name = ''
    quantity = ''
    description = ''
    
    def __init__(self, name, quantity, description):
        self.name = name
        self.quantity = quantity
        self.description = description
    def __str__(self):
        details = ''
        details += f'Name        : {self.name}\n'
        details += f'Quantity    : {self.quantity}\n'
        details += f'Description : {self.description}\n'
        return details
apple = Fruit('Apple', '58', 'Good for health.')
print(apple)Output
Name        : Apple
Quantity    : 58
Description : Good for health.Summary
In this Python Classes and Objects tutorial, we learned how to override __str__() function in a class definition to change the string representation of a class object.

