In Python, you can redefine an operator (also known as operator overloading) for your custom classes by implementing special methods, often called dunder methods (double underscore methods). These methods allow you to define how operators behave when used with instances of your class.
+__add__-__sub__*__mul__/__truediv__==__eq__<__lt__>__gt__<=__le__>=__ge__+=__iadd__[]__getitem__()__call__+ for a Custom Classpythonclass Vector: def __init__(self, x, y): self.x = x self.y = y # Overloading the + operator def __add__(self, other): return Vector(self.x + other.x, self.y + other.y) # Overloading the * operator def __mul__(self, scalar): return Vector(self.x * scalar, self.y * scalar) # Overloading the == operator def __eq__(self, other): return self.x == other.x and self.y == other.y # Overloading the string representation def __str__(self): return f"Vector({self.x}, {self.y})" # Usage v1 = Vector(2, 3) v2 = Vector(4, 5) v3 = v1 + v2 v4 = v1 * 2 print(v3) # Output: Vector(6, 8) print(v4) # Output: Vector(4, 6) print(v1 == Vector(2, 3)) # Output: True
__add__ is called when you use + on instances of your class.__mul__ is called when you use * on instances of your class.__eq__ is called when you use == to compare instances.__str__ is called when you use print() or str() on an instance.Want to see more examples or a specific operator? Let me know!