Beginner LevelPython
What are Dunder (Double Underscore) methods in Python and how do they enable operator overloading?
❓ Interview Prompt: Explain special dunder methods (`__init__`, `__str__`, `__repr__`, `__len__`, `__getitem__`, `__add__`), and operator overloading.
Dunder Methods (short for Double Underscore methods, also known as Magic Methods) are special predefined methods surrounded by leading and trailing double underscores (e.g. '__init__'):
Operator Overloading:
Implementing dunder methods allows custom classes to interface seamlessly with Python built-in functions and operators:
•
'len(obj)' $\rightarrow$ calls 'obj.__len__()'
•
'a + b' $\rightarrow$ calls 'a.__add__(b)'
•
'obj[key]' $\rightarrow$ calls 'obj.__getitem__(key)'
Code Implementation Example
python
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other): # Overloads the + operator!
return Vector(self.x + other.x, self.y + other.y)
def __repr__(self): # Custom developer string representation
return f'Vector({self.x}, {self.y})'
v1 = Vector(2, 4)
v2 = Vector(3, 1)
print(v1 + v2) # Output: Vector(5, 5)💡Overloading the + operator using the __add__ dunder method.
🎯 Interview Key Takeaway
Implement dunder methods like __add__ and __repr__ to make custom objects behave natively with operators and built-in functions.
#Dunder Methods#Magic Methods#OOP#Operator Overloading#Beginner
Back to all Python Questions→