What is the use of the "str" and "repr" methods in Python?

Table of Contants

Introduction

In Python, the __str__ and __repr__ methods are used to define how an object is represented as a string. These methods provide ways to produce string representations of objects, each serving different purposes and contexts.

The __str__ Method

The __str__ method is used to define a human-readable string representation of an object. This method is called by the str() function and the print() function when printing objects. The goal of __str__ is to provide a readable and informative string that is useful for end-users.

Syntax:

Example:

In this example, __str__ provides a user-friendly string representation of the Person object.

The __repr__ Method

The __repr__ method is used to define a detailed and unambiguous string representation of an object that is mainly intended for developers. This method is called by the repr() function and is often used in debugging and logging. The goal of __repr__ is to provide a string that, when passed to eval(), would ideally recreate the object.

Syntax:

Example:

In this example, __repr__ provides a detailed and unambiguous string representation of the Person object.

Key Differences and Uses

  1. Purpose:
    • __str__: Aimed at end-users for creating readable output.
    • __repr__: Aimed at developers for debugging and detailed output.
  2. Output:
    • __str__: Should be readable and provide a clear description of the object.
    • __repr__: Should be precise and ideally include all necessary information to recreate the object.
  3. Fallback:
    • If __str__ is not defined, Python will use __repr__ as a fallback for str().
    • If __repr__ is not defined, Python provides a default representation that includes the object’s memory address.

Example of Fallback Behavior:

Conclusion

The __str__ and __repr__ methods in Python are essential for defining how objects are represented as strings. By implementing __str__, you provide a user-friendly representation of the object, while __repr__ offers a detailed and unambiguous view that is useful for debugging and development. Understanding and utilizing these methods effectively helps in creating clear and maintainable code.

Similar Questions