How to Make Custom Class Printable in Python Easily
To make a custom class printable in Python, define the
__str__ method to return a user-friendly string representation. Optionally, define __repr__ for an unambiguous representation useful for debugging.Syntax
Define the __str__ method inside your class to control what is shown when you print an object. Optionally, define __repr__ to provide a detailed string for debugging.
def __str__(self):returns a readable string.def __repr__(self):returns a detailed string for developers.
python
class ClassName: def __str__(self): return "User-friendly string" def __repr__(self): return "Detailed representation for debugging"
Example
This example shows a Person class with __str__ and __repr__ methods. Printing the object calls __str__, while just typing the object in the console calls __repr__.
python
class Person: def __init__(self, name, age): self.name = name self.age = age def __str__(self): return f"Person named {self.name}, aged {self.age}" def __repr__(self): return f"Person(name={self.name!r}, age={self.age!r})" p = Person("Alice", 30) print(p) p
Output
Person named Alice, aged 30
Person(name='Alice', age=30)
Common Pitfalls
Many beginners forget to define __str__, so printing the object shows a default message like <__main__.ClassName object at 0x...>. Also, confusing __str__ and __repr__ can lead to unclear outputs.
Always define __str__ for user-friendly output and __repr__ for debugging.
python
class Wrong: pass w = Wrong() print(w) # Output is not helpful class Right: def __str__(self): return "Nice output" r = Right() print(r) # Output is nice
Output
<__main__.Wrong object at 0x7f...>
Nice output
Quick Reference
Summary tips:
__str__controls print() output.__repr__controls interactive console output.- Use
!rin f-strings inside__repr__for quotes. - Always return strings from these methods.
Key Takeaways
Define __str__ to customize what print() shows for your class objects.
Define __repr__ to provide a clear, unambiguous string useful for debugging.
If __str__ is missing, print() shows a default, less helpful message.
Use f-strings with !r in __repr__ to show quotes around strings.
Always return strings from __str__ and __repr__ methods.