a shot of dev knowledge

RELATED TAGS

What is the __repr__ method in Python?

In Python, __repr__ is a special method used to represent a class’s objects as a string. __repr__ is called by the repr() built-in function. You can define your own string representation of your class objects using the __repr__ method.

Special methods are a set of predefined methods used to enrich your classes. They start and end with double underscores.

According to the official documentation, __repr__ is used to compute the “official” string representation of an object and is typically used for debugging.

Syntax

object.__repr__(self)

Returns a string as a representation of the object.

Ideally, the representation should be information-rich and could be used to recreate an object with the same value.

Code

Let’s make a class, Person, and define the __repr__ method. We can then call this method using the built-in Python function repr().

# A simple Person class

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __repr__(self):
        rep = 'Person(' + self.name + ',' + str(self.age) + ')'
        return rep


# Let's make a Person object and print the results of repr()

person = Person("John", 20)
print(repr(person))

RELATED TAGS

RELATED COURSES

View all Courses

Keep Exploring