Operator Overloading

Custom operators for classes

Interview Relevant: Advanced OOP

Operator Overloading

Define custom behavior for operators.

Code Examples

Operator overloading with dunder methods.

python
1class Vector:
2    def __init__(self, x, y):
3        self.x, self.y = x, y
4
5    def __add__(self, other):      # +
6        return Vector(self.x + other.x, self.y + other.y)
7
8    def __sub__(self, other):      # -
9        return Vector(self.x - other.x, self.y - other.y)
10
11    def __mul__(self, scalar):     # *
12        return Vector(self.x * scalar, self.y * scalar)
13
14    def __eq__(self, other):       # ==
15        return self.x == other.x and self.y == other.y
16
17    def __lt__(self, other):       # <
18        return (self.x**2 + self.y**2) < (other.x**2 + other.y**2)
19
20    def __repr__(self):
21        return f"Vector({self.x}, {self.y})"
22
23v1 = Vector(1, 2)
24v2 = Vector(3, 4)
25print(v1 + v2)   # Vector(4, 6)
26print(v1 * 3)    # Vector(3, 6)

AI Tutor

Ask about the topic

Sign in Required

Please sign in to use the AI tutor

Sign In