Member-only story

Mastering Python’s str and repr Methods: A Practical Guide

Unlock the Power of Object Representation in Python

Max N
3 min readMar 29, 2024
Photo by David Clode on Unsplash

In the world of Python programming, the str and repr methods play a crucial role in representing objects in a human-readable and unambiguous manner. These built-in methods are essential for debugging, logging, and displaying information about objects in a way that is both informative and easy to understand.

In this article, we'll dive deep into the intricacies of these methods, explore their differences, and provide practical examples to help you master their usage.

The str Method: Crafting User-Friendly Representations

The str method is designed to provide a human-readable representation of an object. It is primarily used for displaying objects in a way that is easily understandable by end-users or for logging purposes.

When you call str(obj) on an object, Python automatically invokes the object's __str__ method, which should return a string representation of the object. Here's an example of how the str method works with a custom class:

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

def __str__(self):
return f"{self.name} ({self.age}…

--

--

Max N
Max N

Written by Max N

A writer that writes about JavaScript and Python to beginners. If you find my articles helpful, feel free to follow.

No responses yet