Operator overloading in Python
Giving a class meaning for +, *, and repr.
class Vector:
def __init__(self, x, y):
self.x, self.y = x, y
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
def __mul__(self, scale):
return Vector(self.x * scale, self.y * scale)
def __repr__(self):
return f"Vector({self.x}, {self.y})"
v = Vector(1, 2) + Vector(3, 4)
w = v * 10
How it works
__add__defines what+does between vectors.__mul__scales the vector by a number.__repr__gives it a readable form.
Keywords and builtins used here
Vectorclassdefreturnself
The run, in numbers
- Lines
- 16
- Characters to type
- 314
- Tokens
- 117
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 67 seconds.
Step 4 of 5 in Protocols & context managers, step 18 of 53 in Pythonic Python.