What Does the Repr Function Do in Python?

Published by Brandon on

You may not even be familiar with the repr() function in python. Let’s look at what this function does with examples.

Simply stated, the repr function returns a string representation of an object in python. let’s check out an example.

Example with a list:

lst = [1, 2, 3, 4, 5, 6]

printed_list = repr(lst)

print(printed_list)

The output is this:

[1, 2, 3, 4, 5, 6]

What happens when we get the repr of a string? Let’s find out:

test = 'test string'

print(repr(test))

And the output is:

'test string'

Notice that the printed value has single quotes around it when printed. If we printed a string without the repr function, there would be no quotes. What ends up happening is the repr function puts double quotes around the string, so it looks like this – “‘test string'”.

Defining the Repr with a Custom Class

Let’s create a class named Dog and then add a Repr method to it. When we use the repr function, that looks for the __repr__() method.

class Dog:
    name = "Rufus"
    age = 3

    def __repr__(self):
        return f'Name: {self.name}, Age: {self.age}'

dog = Dog()

print(repr(dog))

The output from the script will be this:

Name: Rufus, Age: 3
Categories: Python

0 Comments

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *