Member-only story

Understanding repr and str in Python with a Complex Example

Neural pAi
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:

  1. __repr__: It returns a string that, when passed to the eval() 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.
  2. __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 like print() and str(). 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)…

--

--

No responses yet