repr() Built-in Function
Python - repr()
Python repr() built-in function returns a string containing printable representation of the given object.
In this tutorial, we will learn the syntax and usage of repr() built-in function with examples.
Syntax
The syntax of repr() function is
repr(object)
where
Parameter | Mandatory/ Optional | Description |
---|---|---|
object | Mandatory | Any valid Python object. |
Examples
1. String representation of user-defined object
In the following program, we take a user defined class Student
, created an object student1
of type Student
, and printed the output of repr(student1)
.
Python Program
class Student:
def __init__(self, name, age, country):
self.name = name
self.age = age
self.country = country
student1 = Student('Mike', 12, 'Canada')
string_representation = repr(student1)
print(string_representation)
Output
<__main__.Student object at 0x102b70310>
The result is a string with the object type and address enclosed in angular brackets.
2. String representation of a List object
In the following program, we take a list x
, and print the string representation of this list object using repr() function.
Python Program
x = ['apple', 'banana', 'cherry']
string_representation = repr(x)
print(string_representation)
Output
['apple', 'banana', 'cherry']
Unlike the result in our previous example, the string representation is readable and contains the details of the given object. This is because List is a built-in class, and generally for the built-in classes, __repr__() function is defined.
Override String Representation of an User-defined Object
We can override the string representation of an object by defining __repr__() method inside the class definition.
In the following program, we define __repr__()
function in the Student
class. Create a class object of type Student
, and print the string returned by repr() function.
Python Program
class Student:
def __init__(self, name, age, country):
self.name = name
self.age = age
self.country = country
def __repr__(self):
return f"[Name: {self.name}, Age: {self.age}, Country: {self.country}]"
student1 = Student('Ram', 12, 'Canada')
string_representation = repr(student1)
print(string_representation)
Output
[Name: Ram, Age: 12, Country: Canada]
Summary
In this Built-in Functions tutorial, we learned the syntax of the repr() built-in function, how to get the string representation of an object, and how to override it using __repr__() function.