Python’s repr() Function

Learn Python @ Freshers.in

In Python, the repr() function is a valuable tool for obtaining printable representations of objects. This article aims to elucidate its usage, applications, and significance through comprehensive examples.

Understanding repr() Function

The repr() function in Python is used to obtain a printable representation of an object. Its syntax is as follows:

repr(object)

Here, object represents the Python object whose printable representation is to be obtained.

Example 1: Basic Usage

num = 10
print("Printable representation of", num, "is:", repr(num))

Output 1:

Printable representation of 10 is: 10

Example 2: Using with Strings

string = "Hello, World!"
print("Printable representation of", string, "is:", repr(string))

Output 2:

Printable representation of Hello, World! is: 'Hello, World!'

Example 3: Custom Objects

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y
    
    def __repr__(self):
        return f'Point(x={self.x}, y={self.y})'
p = Point(3, 4)
print("Printable representation of", p, "is:", repr(p))

Output 3:

Printable representation of Point(x=3, y=4) is: Point(x=3, y=4)

Points to Remember

  • The repr() function returns a printable representation of an object.
  • It is often used for debugging and logging purposes to provide informative representations of objects.
  • For custom objects, defining a __repr__() method allows customization of the printable representation.
Author: user