Last answered:

16 Nov 2023

Posted on:

14 Nov 2023

1

Resolved: what is the difference between the methods def __str__(self) and def __repr__(self) ?

Both seem to be getting executed when the instance of the class is getting printed

2 answers ( 1 marked as helpful)
Instructor
Posted on:

15 Nov 2023

0

Hey Somnath,


Thanks for reaching out.


In Python, the dunder methods __str__ and __repr__ are special methods used to define how objects of a class are represented as strings. While they serve similar purposes, they are used in different contexts and have distinct intended uses.


The __str__ method is supposed to provide a readable, user-friendly representation of the object. It's invoked when the str() function is used on an object or when the print() function is called to display the object. If __str__ is not implemented in a class, Python falls back to using __repr__ (if it's defined) to get the string representation.


The __repr__ method is meant to provide an unambiguous representation of the object. The goal is to be clear about what the object is, often including information that would allow the recreation of the object. It's typically used for debugging and development, so this representation is usually more for the developer than the end-user. This method is called when the repr() function is used or when an object is displayed in the interactive shell. The Python interpreter uses __repr__ to display the object in the interactive sessions.


Consider the following code snippet:

class Point:
    def __init__(self, x, y):
        self.x, self.y = x, y

    def __repr__(self):
        return f"Point({self.x}, {self.y})"

    def __str__(self):
        return f"({self.x}, {self.y})"

point = Point(2, 3)

In this example, point and repr(point) will output Point(2, 3), which is unambiguous and could be used to recreate the object. On the other hand, str(point) and print(point) will output (2, 3), which is more readable and friendly for the end-user.

Kind regards,

365 Hristina

Posted on:

16 Nov 2023

0

Hi Hristina,


Thanks a lot for the detailed explanation.

Submit an answer