Understanding Python repr Function



In Python, the __repr__() method is a built-in function used to compute the official string representation of an object. It is used in debugging and logging purposes as it provides a detailed and clear representation of an object.

This method is also known as dunder method as it begins with a double underscore in the beginning and at the end. In a class, if __str__() method and the __repr__() method is defined ,then the __str__() method is executed.

Example

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

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

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

obj1=Methods()
print(obj1)

Following is the output of the above code ?

The __repr__ is used in debugging

__repr__() Method with 'datetime' Module

Let's understand the repr() function with the datetime module. For that we need to import the datetime module, and using today(), we can find the date and time. When we use repr() function, we get an informal representation of the string. The eval() built-in function accepts a string and converts it to a datetime object.

Example

Let's try to understand __repr__() method with the 'datatime' module.

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

print(repr(today))
print(eval(repr(today)))

Following is the output of the above code -

2025-04-09 15:27:54.934603
datetime.datetime(2025, 4, 9, 15, 27, 54, 934603)
2025-04-09 15:27:54.934603

Using a Class Without a __repr()__ 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 __repr__() 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 0x7f49ca4ba9c0>
Updated on: 2025-04-14T16:22:45+05:30

688 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements