Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
python3

What is the __repr__ method in Python?

Nouman Abbasi

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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

python
python3

CONTRIBUTOR

Nouman Abbasi
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring