Magic methods (dunder — double underscore) are special methods that start and end with __.
Common magic methods:
Object lifecycle:
__init__(self, ...) — constructor.__repr__(self) — representation for developers.__str__(self) — representation for users.__del__(self) — destructor.Comparison:
__eq__(self, other) — ==.__lt__(self, other) — <.__le__(self, other) — <=.__hash__(self) — for use in dict/set.Arithmetic:
__add__(self, other) — +.__mul__(self, other) — *.__len__(self) — len().Example:
1class Vector:2 def __init__(self, x, y):3 self.x = x4 self.y = y56 def __repr__(self):7 return f"Vector({self.x}, {self.y})"89 def __add__(self, other):10 return Vector(self.x + other.x, self.y + other.y)1112 def __len__(self):13 return (self.x**2 + self.y**2) ** 0.51415v1 = Vector(1, 2)16v2 = Vector(3, 4)17print(v1) # Vector(1, 2)18print(v1 + v2) # Vector(4, 6)19print(len(v1)) # 2.23