Operator Overloading in Python
Operator Overloading in Python
Operator overloading allows you to define custom behavior for built-in operators (+, -, *, /, etc.) when they are
used with objects of your own classes. This makes your objects behave more like built-in types, enabling
- To implement operations specific to the class, such as adding two complex numbers or merging two custom
objects.
Python uses special methods (also called magic or dunder methods) for operator overloading. For example:
|----------|--------------------------|
|+ | __add__(self, other) |
|- | __sub__(self, other) |
|* | __mul__(self, other) |
|/ | __truediv__(self, other) |
| == | __eq__(self, other) |
p1 = Point(2, 3)
p2 = Point(4, 5)
p3 = p1 + p2
p3.display() # Output: Point(6, 8)
Step-by-step Explanation:
2. Overloading +: The __add__ method is defined to take two points and return a new Point whose
4. Using the + Operator: When we do p1 + p2, Python internally calls p1.__add__(p2), which returns a new
- Natural Syntax: You can write p1 + p2 instead of a method call like p1.add(p2).
- Arithmetic: -, *, /