How to use __str__ method in Python

__str__ method is python used for string representation of an object. __str__ always returns a string object, this condition makes __str__ different from __repr__ method that can return any valid python expression and not limited to string object only. In this tutorial we will try to understand use and implementation of __str__ method.

Create a class and instantiate an object without implementing __str__


class Employee(object):

    def __init__(self, name, org, designation):
        self.name = name
        self.org = org
        self.designation = designation

emp1 = Employee("XYZ", 'Public-Org', "Python Developer")

print(emp1)

Output


<__main__.Employee object at 0x000001F74BF8AB70>
   

From the output we can not get any meaningful information about the object, lets modify it with __str__ to get some information about the object.


class Employee(object):

    def __init__(self, name, org, designation):
        self.name = name
        self.org = org
        self.designation = designation

    def __str__(self):
        return f"{self.name} is {self.designation}"

emp1 = Employee("XYZ", 'Public-Org', "Python Developer")

print(emp1)


Output:


XYZ is Python Developer