0
0
PythonHow-ToBeginner · 3 min read

How to Implement __str__ Method in Python for Custom String Output

In Python, implement the __str__ method inside your class to define how its objects are converted to strings. This method should return a readable string that describes the object, which is used when you call print() or str() on the object.
📐

Syntax

The __str__ method is defined inside a class with no arguments except self. It must return a string that represents the object in a human-friendly way.

  • def __str__(self): — method header
  • Return a string describing the object
python
class ClassName:
    def __str__(self):
        return "string representation of the object"
💻

Example

This example shows a Person class with __str__ implemented to print the person's name and age in a friendly format.

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

    def __str__(self):
        return f"Person(name={self.name}, age={self.age})"

p = Person("Alice", 30)
print(p)
Output
Person(name=Alice, age=30)
⚠️

Common Pitfalls

Common mistakes include:

  • Not returning a string from __str__ (it must return a string, not print or return other types).
  • Confusing __str__ with __repr__ (use __str__ for user-friendly output).
  • Forgetting to implement __str__ means printing the object shows a default message like <__main__.ClassName object at 0x...>.

Example of wrong and right ways:

python
class Wrong:
    def __str__(self):
        print("This is wrong")  # Does not return a string

class Right:
    def __str__(self):
        return "This is right"

w = Wrong()
r = Right()
print(str(w))  # This prints None because __str__ returns nothing
print(str(r))  # Correct string output
Output
None This is right
📊

Quick Reference

Remember these tips when implementing __str__:

  • Always return a string.
  • Make the string clear and readable for users.
  • Use f-strings for easy formatting.
  • print(object) calls object.__str__() automatically.

Key Takeaways

Implement __str__(self) in your class to customize string output of objects.
__str__ must return a string, not print or return other types.
Use __str__ for user-friendly descriptions, especially for print() and str().
Without __str__, printing an object shows a default, less readable message.
Use f-strings inside __str__ for clear and simple formatting.