Operator overloading in Python allows you to define how operators behave with user-defined types (classes). This enables you to use operators like +, -, *, etc., with your custom objects, making them behave intuitively.
Here’s a simple tutorial on how to overload operators in Python, with an example.
Step 1: Define a Class
First, let’s define a simple class representing a 2D point.
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return f"Point({self.x}, {self.y})"
Step 2: Overload an Operator
To overload an operator, you need to define a special method in your class. These methods have double underscores (__) around their names. Here are some common operators and their corresponding methods:
+:__add__-:__sub__*:__mul__/:__truediv__
Let’s overload the + operator to add two Point objects.
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return f"Point({self.x}, {self.y})"
def __add__(self, other):
if isinstance(other, Point):
return Point(self.x + other.x, self.y + other.y)
return NotImplemented
Step 3: Use the Overloaded Operator
Now you can create Point objects and use the + operator with them.
p1 = Point(1, 2)
p2 = Point(3, 4)
p3 = p1 + p2
print(p3) # Output: Point(4, 6)
Step 4: Overload Other Operators
You can similarly overload other operators. For example, let’s overload the - operator.
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return f"Point({self.x}, {self.y})"
def __add__(self, other):
if isinstance(other, Point):
return Point(self.x + other.x, self.y + other.y)
return NotImplemented
def __sub__(self, other):
if isinstance(other, Point):
return Point(self.x - other.x, self.y - other.y)
return NotImplemented
Now you can subtract Point objects using the - operator.
p1 = Point(5, 7)
p2 = Point(2, 3)
p3 = p1 - p2
print(p3) # Output: Point(3, 4)
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return f"Point({self.x}, {self.y})"
def __add__(self, other):
if isinstance(other, Point):
return Point(self.x + other.x, self.y + other.y)
return NotImplemented
def __sub__(self, other):
if isinstance(other, Point):
return Point(self.x - other.x, self.y - other.y)
return NotImplemented
# Example usage
p1 = Point(5, 7)
p2 = Point(2, 3)
p3 = p1 + p2
p4 = p1 - p2
print(p3) # Output: Point(7, 10)
print(p4) # Output: Point(3, 4)
