Trusted answers to developer questions

What is the __repr__ method in Python?

Get Started With Machine Learning

Learn the fundamentals of Machine Learning with this free course. Future-proof your career by adding ML skills to your toolkit — or prepare to land a job in AI or Data Science.

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))
  • Line 3: We defined a class with the name of Person.

  • Line 4: We defined a special method __init__() which is called the constructor. It initializes new instances of the class. This constructor takes three parameters: self, name, and age.

  • Lines 8-10: We defined another special method __repr__(). This method returns a string representation of the object by concatenating the string 'Person(', the value of self.name, a comma, the value of self.age, and the string ')'.

RELATED TAGS

python
python3

CONTRIBUTOR

Nouman Abbasi
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?