What does the str() function do in Python Object Oriented Programming?

PythonServer Side ProgrammingProgramming

The __str__ method

__str__ is a special method, like __init__, that returns a 'informal' string representation of an object. It is useful in debugging.

Consider the following code that uses the __str__ method

class Time:
    def __str__(self):
        return '%.2d:%.2d:%.2d' % (self.hour, self.minute, self.second)

When we print an object, Python invokes the str method −

>>> time = Time(7, 36)
>>> print time
Published on 18-Jan-2018 16:32:17