Magic/Dunder Methods (__str__, __repr__)

Introduction

Python provides special methods, often called magic methods or dunder (double underscore) methods, that allow us to define how objects behave in different situations. Among these, __str__ and __repr__ are two important methods used to represent objects as strings.

In this tutorial, we will cover:

  1. What are __str__ and __repr__?
  2. Differences between __str__ and __repr__
  3. How and when to use them
  4. Real-world examples

1. What Are __str__ and __repr__?

__repr__ (Official String Representation)

  • Used for debugging and logging
  • Should return a string that evaluates to a valid object
  • Called when using repr(obj) or in interactive mode

__str__ (User-Friendly String Representation)

  • Used for displaying objects in a readable way
  • Called when using str(obj) or print(obj)
  • Should return a human-readable string

2. Key Differences Between __str__ and __repr__

Feature__repr____str__
PurposeDebugging, developmentUser-friendly output
Output FormatShould be unambiguousReadable and descriptive
Called Byrepr(obj), interactive modestr(obj), print(obj)
Example Output"Student('Amit', 21)""Amit (21 years old)"

3. Implementing __str__ and __repr__

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

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

    def __str__(self):
        return f"{self.name} ({self.age} years old)"

# Creating an object
s1 = Student("Amit", 21)

# Using repr()
print(repr(s1))   # Output: Student('Amit', 21)

# Using str()
print(str(s1))    # Output: Amit (21 years old)

# Implicit calls
print(s1)         # Output: Amit (21 years old)
s1                # Output: Student('Amit', 21)

__repr__ is used for debugging and should return a valid Python expression, while __str__ is more readable for end-users.


4. When to Use __repr__ and __str__?

Use __repr__ when:

  • You need an unambiguous string for debugging/logging
  • The output should allow object reconstruction

Use __str__ when:

  • You need a human-readable representation
  • The object should be printed in a friendly way

5. Real-World Example: Employee Class

class Employee:
    def __init__(self, name, salary):
        self.name = name
        self.salary = salary

    def __repr__(self):
        return f"Employee('{self.name}', {self.salary})"

    def __str__(self):
        return f"{self.name} earns ₹{self.salary}/month"

e1 = Employee("Priya", 50000)

print(repr(e1))  # Output: Employee('Priya', 50000)
print(str(e1))   # Output: Priya earns ₹50000/month

The __repr__ method provides a developer-friendly format, while __str__ makes the output more user-friendly.


6. Summary

__repr__ → Used for debugging, should be unambiguous
__str__ → Used for display, should be user-friendly
If __str__ is not defined, Python falls back to __repr__