
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:
len(inv): the total number of things (sum of counts).inv[name]: the count forname, or0if it's missing.name in inv:Trueif the count is more than 0.a + b: a newInventorywith counts added together (don't changeaorb). ReturnNotImplementedifbisn't anInventory.a == b:Truewhen the items are equal (NotImplementedfor non-Inventories).
Complete Inventory, which stores item counts in self.items:
len(inv): the total number of things (sum of counts).inv[name]: the count forname, or0if it's missing.name in inv:Trueif the count is more than 0.a + b: a newInventorywith counts added together (don't changeaorb). ReturnNotImplementedifbisn't anInventory.a == b:Truewhen the items are equal (NotImplementedfor non-Inventories).
main.py Python sleeping
Press Run to try your code, then Check to test it.