__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
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.
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.
Let’s make a class,
Person, and define the
__repr__ method. We can then call this method using the built-in Python function
# 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))
View all Courses