What if your objects could act just like numbers or strings without extra effort?
Why Purpose of magic methods in Python? - Purpose & Use Cases
Imagine you have a class for a custom object, like a book, and you want to add two books together to get a combined book or print a book nicely. Without magic methods, you would have to write separate functions for each action and call them manually every time.
This manual way is slow and confusing because you must remember to call the right function each time. It also makes your code messy and hard to read. You lose the natural feel of using operators like + or functions like print directly on your objects.
Magic methods let you define how your objects behave with built-in Python operations. You can make your objects respond to +, print, or even compare with others naturally. This makes your code cleaner, easier to read, and more powerful.
def add_books(book1, book2): return book1.pages + book2.pages print_book(book) # custom function needed
class Book: def __init__(self, pages): self.pages = pages def __add__(self, other): return Book(self.pages + other.pages) def __str__(self): return f"Book with {self.pages} pages" book1 = Book(100) book2 = Book(150) print(book1 + book2)
It enables your custom objects to work seamlessly with Python's built-in operations, making your code intuitive and expressive.
Think of a shopping cart object that you can add items to using +, or a date object that you can compare with < or > directly, just like built-in types.
Magic methods let objects behave like built-in types.
They make code cleaner and easier to use.
They allow natural use of operators and functions on your objects.