Dunder Methods
Magic methods like __str__, __repr__
Interview Relevant: Python internals
Dunder Methods
Special methods for operator overloading.
Code Examples
Magic/dunder methods.
python
1class Vector:
2 def __init__(self, x, y):
3 self.x, self.y = x, y
4
5 def __repr__(self):
6 return f"Vector({self.x}, {self.y})"
7
8 def __str__(self):
9 return f"({self.x}, {self.y})"
10
11 def __add__(self, other):
12 return Vector(self.x + other.x, self.y + other.y)
13
14 def __eq__(self, other):
15 return self.x == other.x and self.y == other.y
16
17 def __len__(self):
18 return 2
19
20 def __getitem__(self, index):
21 return (self.x, self.y)[index]
22
23v1 = Vector(1, 2)
24v2 = Vector(3, 4)
25print(v1 + v2) # (4, 6) - uses __add__
26print(v1 == v2) # False - uses __eq__
27print(v1[0]) # 1 - uses __getitem__