Member-only story
Understanding repr and str in Python with a Complex Example
2 min readMar 27, 2023
Introduction:
In Python, understanding the difference between the special methods __repr__
and __str__
is crucial for creating clear and concise string representations of objects. In this article, we'll explore the differences between these two methods, their use cases, and a complex example to illustrate their functionalities.
repr vs str:
__repr__
: It returns a string that, when passed to theeval()
function, can recreate the object. It is meant to be an unambiguous representation of the object and is mainly used for debugging and development purposes. If__str__
is not defined for a class, Python will fall back to using__repr__
when attempting to display the object.__str__
: It returns a string that provides a nicely formatted, human-readable description of the object. It is intended for end-users and is called by built-in functions likeprint()
andstr()
. If__str__
is not defined, Python will use__repr__
as a fallback.
Complex Example:
Now, let’s consider a complex example to illustrate their differences:
class ComplexNumber:
def __init__(self, real, imaginary):
self.real = real
self.imaginary = imaginary
def __repr__(self)…