Operator Overloading
Introduction to OOP's
Class
Object
Constructor
Instance Variables
Class Variables
Instance Methods
self Keyword
Encapsulation
Public Members
Protected Members
Private Members
Inheritance
Single Inheritance
Multiple Inheritance
Multilevel Inheritance
Hierarchical Inheritance
Hybrid Inheritance
super() Function
Polymorphism
Method Overriding
Duck Typing
Abstraction
Abstract Class
Abstract Method
Class Method
Static Method
Special Methods
_str_ Method
Operator Overloading
Composition
Aggregation
Association
Method Resolution Order
Object Class
issubclass() and isinstance()
Property Decorator
Setter Method with @property
Destructor
Inner Class
Complete Mini Example
Operator Overloading
29. Operator Overloading
Operator overloading allows operators such as + to work with user-defined objects through special methods. This is implemented with methods like __add__().
Syntax
def __add__(self, other):
pass
Example
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return Point(self.x + other.x, self.y + other.y)
def __str__(self):
return f"({self.x}, {self.y})"
p1 = Point(2, 3)
p2 = Point(4, 5)
print(p1 + p2)
Output
(6, 8)
Example
Executing...
❌ Error:
✅ Output:
// Click Run ▶ to execute
🏋️ Test Yourself With Exercises
Take our quiz on Operator Overloading to test your knowledge.
Browse Quizzes »