Special methods (those that start and end with double underscores) let your classes integrate with the language syntax: len(x), x[i], a in x, x(...), for e in x.
class Vector:
def __init__(self, *values):
self.values = list(values)
def __len__(self):
return len(self.values)
def __getitem__(self, i): # v[i] and also slices and for
return self.values[i]
def __contains__(self, x): # x in v
return x in self.values
def __call__(self, k): # v(k): scalar
return Vector(*(x * k for x in self.values))
def __repr__(self):
return f"Vector{tuple(self.values)}"
v = Vector(1, 2, 3)
print(len(v), v[0], v[-1], 2 in v, 9 in v) # 3 1 3 True False
print(v(10)) # Vector(10, 20, 30)
print([x for x in v]) # [1, 2, 3] (iterable thanks to __getitem__)
print(callable(v), callable(5)) # True False
# Command: actions as objects that can be undone
class Add:
def __init__(self, target, n):
self.target, self.n = target, n
def do(self):
self.target.append(self.n)
def undo(self):
self.target.pop()
items, history = [], []
for n in (1, 2, 3):
command = Add(items, n)
command.do()
history.append(command)
history.pop().undo()
print(items) # [1, 2]
| Method | Triggered by |
|---|---|
__call__(self, ...) | obj(...) |
__getitem__(self, k) | obj[k] (and, if there is no __iter__, for) |
__setitem__(self, k, v) | obj[k] = v |
__len__(self) | len(obj) |
__contains__(self, x) | x in obj |
__iter__(self) | for e in obj |
- An object with
__call__is a function with memory: it serves for polynomials, filters, counters or decorators with state. - With
__getitem__you can accept keys of any type, including tuples (m[i, j]) and *slices* (v[1:3]). - Command: each action is an object with
do()andundo(). With a stack of executed commands you implement undo/redo in an editor.
You practice it in A polynomial called like a function, Sparse matrix with magic methods and Editor with undo (Command).