Section 1/4__str__ — Human-Readable Output
__str__ — Human-Readable Output
Python calls __str__ when you use print(obj) or str(obj). Without it, you get something like <__main__.Student object at 0x7f...>.
Dunder Methods
Python has special methods surrounded by double underscores — called dunder methods(short for "double under"). They let you define how your objects behave with built-in operations like print(), ==, and sorting.
__str__ — Human-Readable Output
Python calls __str__ when you use print(obj) or str(obj). Without it, you get something like <__main__.Student object at 0x7f...>.
class Book:
def __init__(self, title, author):
self.title = title
self.author = author
def __str__(self):
return f"{self.title} by {self.author}"
b = Book("1984", "Orwell")
print(b) # → 1984 by Orwell→
1984 by Orwell