Sign In
Sign In

How To Use the __str__() and __repr__() Methods in Python

How To Use the __str__() and __repr__() Methods in Python
Hostman Team
Technical writer
Python
26.07.2024
Reading time: 4 min

In Python, the __str__() and __repr__() methods are special methods used to define how objects are represented as strings. These methods are crucial for debugging and logging, making it easier to understand the output of objects. This tutorial provides a comprehensive guide on how to use these methods effectively.

Understanding the __str__() Method

The __str__() method in Python is used to create a string representation of an object that is readable and user-friendly. This method is invoked when str() or print() functions are called on an object.

Syntax

class ClassName:
    def __str__(self):
        return "string_representation"

Example

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

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

person = Person("Alice", 30)
print(person)  # Output: Person(name=Alice, age=30)

Output:

Image1

Understanding the __repr__() Method

The __repr__() method is used to create a string representation of an object that is more detailed and unambiguous. This method is intended for developers and is used when repr() function is called, or when the object is inspected in the interactive interpreter.

Syntax

class ClassName:
    def __repr__(self):
        return "detailed_representation"

Example

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})"

person = Person("Alice", 30)
print(repr(person))  # Output: Person(name='Alice', age=30)

Output:

Image3

Key Differences Between __str__() and __repr__()

Purpose:

  • __str__() is for creating a readable representation of an object for end-users. 
  • __repr__() is for creating a detailed and precise representation for developers.

Usage:

  • __str__() is called by the print() and str() functions.
  • __repr__() is called by the repr() function and the interactive interpreter.

Output:

  • __str__() should be user-friendly and easy to read.
  • __repr__() should be unambiguous and often includes additional information useful for debugging.

Best Practices for Using __str__() and __repr__()

  1. Implement Both Methods: It is recommended to implement both __str__() and __repr__() methods to provide clear and useful string representations of objects.
  2. Ensure Readability: Make sure that the output of __str__() is easy to read and understand.
  3. Include All Relevant Information: The __repr__() method should include all necessary details about the object for debugging purposes.
  4. Use F-strings: Utilize Python f-strings for better readability and performance when formatting strings.

Examples of Using __str__() and __repr__()

Example 1: Basic Class Implementation

class Car:
    def __init__(self, make, model, year):
        self.make = make
        self.model = model
        self.year = year

    def __str__(self):
        return f"{self.year} {self.make} {self.model}"

    def __repr__(self):
        return f"Car(make='{self.make}', model='{self.model}', year={self.year})"

car = Car("Toyota", "Corolla", 2020)
print(car)          # Output: 2020 Toyota Corolla
print(repr(car))    # Output: Car(make='Toyota', model='Corolla', year=2020)

Output:

7b8b5edc F849 43f6 9223 Ca35837f7f9c

Example 2: Customizing String Representation

class ComplexNumber:
    def __init__(self, real, imag):
        self.real = real
        self.imag = imag

    def __str__(self):
        return f"{self.real} + {self.imag}i"

    def __repr__(self):
        return f"ComplexNumber(real={self.real}, imag={self.imag})"

complex_num = ComplexNumber(3, 4)
print(complex_num)       # Output: 3 + 4i
print(repr(complex_num)) # Output: ComplexNumber(real=3, imag=4)

Output:

Daee7e52 F180 479c B9f0 E81bc01ec8df

Conclusion

The __str__() and __repr__() methods in Python play a significant role in providing meaningful string representations of objects. Implementing these methods enhances the readability and debuggability of code, making it easier to work with complex objects. By following the best practices outlined in this tutorial, developers can effectively use these methods to improve their Python applications.

Python
26.07.2024
Reading time: 4 min

Do you have questions,
comments, or concerns?

Our professionals are available to assist you at any moment,
whether you need help or are just unsure of where to start
Email us