How can a class produce useful text instead of a default object address? Define __str__ for readable instance output and __repr__ for representation that describes how the instance was created. section 8.4 section 8.4.1 section 8.4.2
Choose the conversion method according to where the text will appear:
- Override __str__ as an instance method that returns a str containing descriptive attributes. print(task), str(task), and f"{task}" use this representation. section 8.4.1
- Override __repr__ as an instance method that returns a string describing instantiation. Interactive console display and repr(task) use this representation. section 8.4.2
- Keep __str__ readable for users and __repr__ informative for developers; defining both gives users and developers proper representations. section 8.6
A readable Task instance
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}" def __repr__(self): return f"Task({self.title!r}, {self.desc!r}, {self.urgency})" Task("Laundry", "Wash clothes", 3) # Task('Laundry', 'Wash clothes', 3) print(task) # Laundry: Wash clothes, urgency level 3 section 8.4.1 section 8.4.2
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}"
Inspect the complete __str__ implementation for a Task class and its formatted attribute output. section 8.4.1

