Operator overloading in Python allows custom classes to define the behavior of operators (like +, -, *, etc.) when used with instances of the class. This feature is useful for creating intuitive and readable code, especially when dealing with user-defined objects.
1. What is Operator Overloading?
Operator overloading is the practice of defining or overriding the default behavior of operators in Python to work with custom objects. It involves implementing special methods in a class that correspond to the operators you want to overload.
2. Special Methods for Operator Overloading
Python uses special methods (also known as magic methods or dunder methods) to implement operator overloading. These methods are prefixed and suffixed with double underscores. Here are some common ones:
__add__(self, other)
: Defines behavior for the+
operator.__sub__(self, other)
: Defines behavior for the-
operator.__mul__(self, other)
: Defines behavior for the*
operator.__eq__(self, other)
: Defines behavior for the==
operator.__lt__(self, other)
: Defines behavior for the<
operator.__str__(self)
: Defines the string representation of the object (used byprint()
).
3. Example: Overloading the Addition Operator
Here's an example of how to overload the +
operator in a custom class:
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
def __str__(self):
return f"Vector({self.x}, {self.y})"
# Example usage
v1 = Vector(2, 3)
v2 = Vector(4, 5)
result = v1 + v2
print(result) # Output: Vector(6, 8)
4. Example: Overloading Comparison Operators
Overloading comparison operators like ==
and <
can be useful for custom objects:
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
def __eq__(self, other):
return (self.width == other.width) and (self.height == other.height)
def __lt__(self, other):
return (self.width * self.height) < (other.width * other.height)
def __str__(self):
return f"Rectangle({self.width}, {self.height})"
# Example usage
rect1 = Rectangle(3, 4)
rect2 = Rectangle(3, 4)
rect3 = Rectangle(5, 6)
print(rect1 == rect2) # Output: True
print(rect1 < rect3) # Output: True
5. Summary
Operator overloading in Python allows you to define how operators work with instances of your custom classes. By implementing special methods in your class, you can make operations involving your objects intuitive and natural. This can lead to more readable and expressive code.