- __mul__
- __rmul__
Opearator overloading
examples/oop/rect/shapes.py
import copy class Rect: def __init__(self, w, h): self.width = w self.height = h def __str__(self): return 'Rect[{}, {}]'.format(self.width, self.height) def __mul__(self, other): o = int(other) new = copy.deepcopy(self) new.height *= o return new
examples/oop/rect/rect.py
import shapes r = shapes.Rect(10, 20) print(r) print(r * 3) print(r) print(4 * r)
Rect[10, 20] Rect[10, 60] Rect[10, 20] Traceback (most recent call last): File "rect.py", line 8, in <module> print(4 * r) TypeError: unsupported operand type(s) for *: 'int' and 'Rect'
In order to make the multiplication work in the other direction, one needs to implement the __rmul__ method.