Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Opearator overloading

  • mul
  • rmul
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
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.