Learning Sections show
Operator Overloading in Python
Operator overloading in Python allows you to define custom behavior for operators when they are used with user-defined classes. This makes your objects behave more like built-in types, which can lead to more intuitive and readable code. Operator overloading is implemented by defining special methods, also known as magic methods or dunder methods (because they begin and end with double underscores).
For example, to overload the addition operator +
, you need to define the __add__
method in your class.
Example: Overloading the Addition Operator
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return Point(self.x + other.x, self.y + other.y)
def __repr__(self):
return f"Point({self.x}, {self.y})"
p1 = Point(1, 2)
p2 = Point(3, 4)
p3 = p1 + p2
print(p3) # Output: Point(4, 6)
Explanation:
In the example above, the __add__
method is defined to overload the addition operator +
. When we create two instances of the Point
class and add them using p1 + p2
, Python calls the __add__
method, which returns a new Point
instance with the coordinates summed.
Other Common Operators
Here are some other common operators and their corresponding magic methods:
+
:__add__(self, other)
-
:__sub__(self, other)
*
:__mul__(self, other)
/
:__truediv__(self, other)
//
:__floordiv__(self, other)
%
:__mod__(self, other)
**
:__pow__(self, other)
==
:__eq__(self, other)
!=
:__ne__(self, other)
>
:__gt__(self, other)
<
:__lt__(self, other)
>=
:__ge__(self, other)
<=
:__le__(self, other)
Example: Overloading Comparison Operators
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __eq__(self, other):
return self.age == other.age
def __lt__(self, other):
return self.age < other.age
person1 = Person("Alice", 30)
person2 = Person("Bob", 25)
person3 = Person("Charlie", 30)
print(person1 == person3) # Output: True
print(person1 < person2) # Output: False
Explanation:
In this example, we overload the equality operator ==
using the __eq__
method and the less than operator <
using the __lt__
method. This allows us to compare Person
objects based on their age
attribute.