Member-only story
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}…