+91 81900 98289

Python __repr__

This Python __repr__ lesson is for a beginner. Read the short notes, run each example, then change one name or number and run it again.

__repr__ returns the text a developer should see in a log or a debugger. Aim for text that shows how to rebuild the object.

If __str__ is missing, print falls back to __repr__.

Example 1: Start here

repr() calls __repr__ directly. print calls __str__ first.

class Score: # a template for objects def __init__(self, value): # runs when you create the object self.value = value # store this on the object def __repr__(self): # define the function; it runs when you call it return "Score(" + str(self.value) + ")" # send this value back to the caller print(repr(Score(82)))

Example 2: A rebuild hint

repr should look like the code that could rebuild the object.

class Course: # a template for objects def __init__(self, title): # runs when you create the object self.title = title # store this on the object def __repr__(self): # define the function; it runs when you call it return "Course(" + repr(self.title) + ")" # send this value back to the caller print(repr(Course("Python")))

Example 3: str falls back to repr

If __str__ is missing, print uses __repr__.

class Course: # a template for objects def __repr__(self): # define the function; it runs when you call it return "Course('Python')" # send this value back to the caller print(Course())

Example 4: Show a list of objects

Printing a list calls repr on each item, not str.

class Course: # a template for objects def __init__(self, title): # runs when you create the object self.title = title # store this on the object def __repr__(self): # define the function; it runs when you call it return "Course(" + repr(self.title) + ")" # send this value back to the caller print([Course("Python"), Course("SQL")])
repr() calls __repr__ directly. print calls __str__ first.
Call Now 81900 98289