Magic/Dunder MethodsAdvanced
1Question 1 of 1
pythonWhat are Magic / Dunder Methods in Python and how do they enable operator overloading?
Explanation & Concept
Dunder (Double Underscore) methods allow custom classes to hook into Python's built-in syntax: • `__str__` / `__repr__`: String representations. • `__len__`: Hook for `len(obj)`. • `__add__`: Hook for the `+` operator. • `__getitem__`: Hook for index access `obj[key]`.
Code Example
python
class Vector:
def __init__(self, x: float, y: float):
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(2, 3)
v2 = Vector(5, 7)
print(v1 + v2) # Vector(7, 10)How It Works & Key Takeaways
Implementing dunder methods makes custom objects feel like native Python types, integrating seamlessly with standard operators.
Mock Test · 1 Questions · Optional
Ready for Memory Management & GC?
Take a quick test to evaluate yourself, or move straight to the next module.
Advanced1 questions