__str__Easy Examples

Returns a human-readable string representation (used by print and str())

Implementing __str__

Basic implementation of __str__ in a class.

python
class Product:
    def __init__(self, name, price):
        self.name = name
        self.price = price

    def __str__(self):
        return f"{self.name}: ${self.price:.2f}"

p = Product("Widget", 9.99)
print(p)
print(str(p))

__str__ returns a human-readable string representation (used by print and str()). Implementing it lets you customize how Python interacts with your objects.

__str__ in action

Seeing __str__ called by Python's built-in operations.

python
# How Python calls __str__ automatically
class Demo:
    def __init__(self, value):
        self.value = value

    def __str__(self):
        print(f"__str__ was called!")
        return f"Demo({self.value})"

d = Demo(42)
# This triggers __str__:
print(str(d))

Python automatically calls __str__ when you use the corresponding operator or function on your object.

Want to try these examples interactively?

Open Easy Playground