Magic methods (or Dunder methods)
These are the methods, that start with __
e.g. __init__
, __add__
.
They are useful, because you can e.g. define a class and its __add__
method. Without the special method, you couldn’t do object_a + object_b
. This method allows you to define the operation performed when a +
operand is used.
You could do the previously mentioned thing with this snippet:
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
v1 = Vector(10, 20)
v2 = Vector(40, 50)
v3 = v1 + v2
What magic methods are there?
There are way too many to cover here. A cheat sheet shows a couple of them, docs show the rest.