Lesson 29 of 55
PythonMagic Methods and Dunder
20 minutes
Course progress53%
What you'll learn
Keep these ideas in mind as you work through the lesson.
Lesson 29 of 55
Python20 minutes
Keep these ideas in mind as you work through the lesson.
Magic (or dunder) methods are special hooks that let your objects integrate with Python’s built‑in syntax. They always start and end with double underscores (__).
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return f'Vector({self.x}, {self.y})'
def __len__(self):
return 2
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
v1 = Vector(1, 2)
v2 = Vector(3, 4)
print(v1) # Vector(1, 2)
print(len(v1)) # 2
print(v1 + v2) # Vector(4, 6)
Implementing the appropriate dunder methods makes your classes feel like native Python types.