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


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
07:36:00

Updated on: 15-Jun-2020

308 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements