24. Operator Overloading
1. Overloading + for Adding Two Objects
Copy
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 __repr__(self):
return f"Vector({self.x}, {self.y})"
v1 = Vector(1, 2)
v2 = Vector(3, 4)
print(v1 + v2) # Vector(4, 6)2. Overloading - for Subtraction
Copy
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __sub__(self, other):
return Vector(self.x - other.x, self.y - other.y)
def __repr__(self):
return f"Vector({self.x}, {self.y})"
v1 = Vector(5, 7)
v2 = Vector(2, 3)
print(v1 - v2) # Vector(3, 4)3. Overloading * for Scalar Multiplication
Copy
4. Overloading / for Scalar Division
Copy
5. Overloading == for Equality Comparison
Copy
6. Overloading > for Greater Than Comparison
Copy
7. Overloading % for Custom Modulo Behavior
Copy
8. Overloading len() Using __len__
Copy
9. Overloading String Representation Using __str__
Copy
10. Overloading in Using __contains__
Copy
These examples illustrate how Python's special methods (dunder methods) allow you to redefine the behavior of built-in operators to work with custom classes, providing an intuitive and readable API.
Last updated