How can a class show useful information when you print one of its instances? Without a custom string representation, printing an instance may show only its class and memory address. Define __str__ to provide a descriptive, user-oriented alternative. section 8.4.1
Listing 8.10 Overriding __str__ in a class
class Task:
def __init__(self, title, desc, urgency):
self.title = title
self.desc = desc
self.urgency = urgency
def __str__(self):
return f"{self.title}: {self.desc}, urgency level {self.urgency}"
A Task instance stores a title, description, and urgency. Its __str__ method combines those attributes into a readable string and returns it. section 8.4.1
Display an instance
With task = Task("Laundry", "Wash clothes", 3), print(task) outputs Laundry: Wash clothes, urgency level 3. An f-string such as f"Next Task - {task}" uses the same method. Use str(task) when you want the string explicitly. section 8.4.1
Keep these distinctions in mind:
- __str__ is an instance method. It must return a str containing descriptive information about that instance. section 8.4.1
- __repr__ serves developers inspecting an object, including in an interactive console; __str__ serves ordinary display. In f-strings, {instance!r} requests __repr__, while {instance!s} requests __str__. section 8.4.3
- Consider implementing both methods. If you implement only __repr__, Python uses it when __str__ is absent. section 8.4.4
Listing 9.2 Adding a custom method
class Direction(Enum):
NORTH = 0
SOUTH = 1
EAST = 2
WEST = 3
def __str__(self):
return self.name.lower()
def move_to(direction: Direction, distance: float):
if direction in Direction:
message = f"Go to the {direction} for {distance} miles"
else:
message = "Wrong input for direction"
print(message)
move_to(Direction.NORTH, 3)
# output: Go to the north for 3 miles
The same technique works for enumeration members: returning self.name.lower() changes an f-string’s displayed direction from Direction.NORTH to north. section 9.1.4


