Code

Dunder Methods

Python's syntax is a set of hooks. a + b calls a.__add__(b), len(x) calls x.__len__(), x[k] calls x.__getitem__(k). Define these dunder (double-underscore) methods and your objects plug straight in.

You write Python calls
a + b a.__add__(b)
a == b a.__eq__(b)
len(a) a.__len__()
a[k] a.__getitem__(k)
k in a a.__contains__(k)
a(x) a.__call__(x)
repr(a) a.__repr__()
class Vec:
    def __init__(self, x, y):
        self.x, self.y = x, y
    def __add__(self, other):
        if not isinstance(other, Vec):
            return NotImplemented
        return Vec(self.x + other.x, self.y + other.y)
    def __call__(self, scale):
        return Vec(self.x * scale, self.y * scale)
    def __repr__(self):
        return f"Vec({self.x}, {self.y})"

Vec(1, 2) + Vec(3, 4)   # Vec(4, 6)
Vec(1, 2)(10)           # Vec(10, 20)

Returning the special value NotImplemented says "I don't know how"; Python then tries the other operand and finally raises TypeError.

Assignment

Complete Inventory, which stores item counts in self.items:

  1. len(inv): the total number of things (sum of counts).
  2. inv[name]: the count for name, or 0 if it's missing.
  3. name in inv: True if the count is more than 0.
  4. a + b: a new Inventory with counts added together (don't change a or b). Return NotImplemented if b isn't an Inventory.
  5. a == b: True when the items are equal (NotImplemented for non-Inventories).