Operator Overloading
In Python, operators like +
, -
, and ==
have special meanings for built-in data types. For example:
+
-
==
adds numbers:+ 3 + 4
gives7
.
can also join strings:+ "Hello" + "World"
gives"HelloWorld"
.
But what if you have a custom object, and you want +
==
Why use operator overloading?
It makes your code more intuitive and readable. Instead of calling a method like add_objects(obj1, obj2)
obj1 + obj2
How does it work?
Python has special methods (also called "magic methods") that correspond to operators. For example:
: Defines the behavior of the__add__ operator.+
: Defines the behavior of the__sub__ operator.-
: Defines the behavior of the__eq__ operator.==
You override these methods in your class to customize operator behavior.
Example: Adding two custom objects
Imagine you’re working with a Book
class where each book has a certain number of pages. You want to "add" two books together to get the total number of pages.
Step 1: Create the class
class Book:
def __init__(self, title, pages):
self.title = title
self.pages = pages
Step 2: Overload the +
operator
+
Use the __add__
+
with two Book
objects.
def __add__(self, other):
return self.pages + other.pages
Step 3: Try it out
book1 = Book("Python Basics", 300)
book2 = Book("Advanced Python", 450)
total_pages = book1 + book2
print(f"Total pages: {total_pages}") # Output: Total pages: 750
Here’s what happens:
- When you write
, Python automatically callsbook1 + book2
.book1.__add__(book2)
Example: Comparing two objects
What if you want to check if two books have the same number of pages using ==
?__eq__
def __eq__(self, other):
return self.pages == other.pages
Now, you can do this:
book3 = Book("Python Basics", 300)
print(book1 == book3) # Output: True (same number of pages)
Real-life analogy
Think of operator overloading as teaching your object how to behave with certain actions. For example:
for numbers means add, but for strings, it means combine.+ - By overloading operators, you decide what these actions mean for your objects.
Key points to remember:
-
Operator overloading doesn’t change Python’s rules. It just adds your custom logic for your objects.
- You can overload operators like:
with+ __add__
with- __sub__
with== __eq__
with* __mul__
- And more!