Note

Python - Magic Method __str__ - Create human-readable object representation


Understanding the Python __str__ Magic Method / Dunder Method with Examples

Magic Method __str__ specify what should be returned when we will call str() or print() on our class instance. This method needs to return a string.

It should return human-readable representation of your class. It is meant to help you understand better given object that you are working with.

It shouldn't be confused with __repr__ magic method. The __repr__ method, by contrast, is intended for a more developer-focused, technical representation.


class MyClass:
    def __init__(self, my_int: int) -> None:
        self.my_int = my_int

    def __str__(self) -> str:
        return f"MyClass - {self.my_int}"


my_class_instance = MyClass(1)

print(my_class_instance)  # MyClass - 1
print(MyClass(2))  # MyClass - 2

Output:

MyClass - 1
MyClass - 2

When to Use the __str__ Method

You should define __str__ in your class when you want to provide a friendly, human-readable description of your objects, making it easier to understand the output when printed.


Here you can take a look at a more practical example:

class Product:
    def __init__(self, name: str, price: float) -> None:
        self.name = name
        self.price = price

    def __str__(self) -> str:
        return f"{self.name} costs ${self.price:.2f}"  # :.2f specifies precision of float number

product = Product("Laptop", 999.99)

print(product)  # Laptop costs $999.99

Output:

Laptop costs $999.99

I hope you found this helpful! If you have any feedback, questions or requests, please reach out to me through Contact page!

Thank You Image


You might also be interested in: