Understanding the str Function in Python OOP



In Python, the __str__() method is used to compute the informal or human readable string representation of an object. This method is called by the built-in print(), string and format() functions. This method is called by the implementation of the default __format__() method and the built-in function print(). This method returns the string object.

In a class, if the __str__() method is not defined, Python will fall back to using the __repr__() method. If neither of these dunder methods is defined, the class will return the default string representation of the object

Example

Here, we have created a class named Methods and defined the __str__() method. When we execute the code, the output will be the string returned by the __str__() method ?

class Methods:
   def __init__(self):
      self.method1='wrapper'
      self.method2='string'

   def __str__(self):
      return "The __str__() is used in debugging"

obj1=Methods()
print(obj1)

Following is the output of the above code ?

The __str__() is used in debugging

The __str__() Method with 'datetime' Module

Let's understand the str() function using the datetime module. First, we need to import the datetime module and then use the today() method to get the current date and time. When we apply the str() function to the result, we get an informal, human-readable string representation of the date and time.

Example

Let's try to understand __str__() method with 'datatime' module -

import datetime
today=datetime.datetime.today()
print(today)
print(str(today))

Following is the output of the above code ?

2025-04-09 17:03:18.488095
2025-04-09 17:03:18.488095

Using a Class Without a __str()__ Method

In a class, if the __repr__() and __str__() methods are not defined, the default string representation of the object is returned, which includes the class name and the object's memory address in hexadecimal format.

Example

In the following example, we have defined a class without __str__() method, which returned default representation of the object -

class Methods:
   def __init__(self):
      self.method1='wrapper'
      self.method2='string'

obj1=Methods()
print(obj1)

Following is the output of the above code ?

<__main__.Methods object at 0x7f401d28aa80>
Updated on: 2025-04-14T16:23:59+05:30

521 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements