0
0
PythonHow-ToBeginner · 3 min read

How to Implement __repr__ Method in Python: Simple Guide

In Python, implement the __repr__ method inside your class to return a string that clearly represents the object, usually including its class name and important attributes. This string helps developers understand the object when printed or inspected in debugging.
📐

Syntax

The __repr__ method is defined inside a class and must return a string. This string should ideally be a valid Python expression that can recreate the object or at least show useful information about it.

  • def __repr__(self): defines the method.
  • Return a string describing the object.
python
class MyClass:
    def __repr__(self):
        return '<MyClass representation>'
💻

Example

This example shows a class Person with name and age attributes. The __repr__ method returns a string that includes the class name and these attributes, making it easy to see the object's state.

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

    def __repr__(self):
        return f"Person(name='{self.name}', age={self.age})"

p = Person('Alice', 30)
print(repr(p))
Output
Person(name='Alice', age=30)
⚠️

Common Pitfalls

Common mistakes when implementing __repr__ include:

  • Returning a string that is not informative or too vague.
  • Not including important attributes that describe the object.
  • Returning a string that is not valid Python code (though this is a recommendation, not a strict rule).

Always ensure __repr__ returns a string, not other types.

python
class BadExample:
    def __repr__(self):
        return '123'  # Wrong: must return a string

class GoodExample:
    def __repr__(self):
        return 'GoodExample()'  # Correct: returns a string
📊

Quick Reference

AspectDescription
Method name__repr__
PurposeReturn string representation for debugging
Return typeString
Recommended contentClass name and key attributes
Use caseUsed by repr() and in interactive shells

Key Takeaways

Implement __repr__ to return a clear, informative string about the object.
The returned string should ideally look like valid Python code to recreate the object.
Always return a string, never other data types.
Include important attributes to help understand the object's state.
Use __repr__ for debugging and logging to get useful object info.