typestar

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

  1. __add__ defines what + does between vectors.
  2. __mul__ scales the vector by a number.
  3. __repr__ gives it a readable form.

Keywords and builtins used here

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.

Type this snippet

Step 4 of 5 in Protocols & context managers, step 18 of 53 in Pythonic Python.

← Previous Next →

Operator overloading in other languages