Operator Overloading in Python

Level 4248 keystrokes

This overloads the + operator using __add__. When you use + between Vector objects, Python calls the __add__ method.

Python code

# Define a 2D vector class
1class Vector:
# The constructor takes the x and y components
2 def __init__(self, x, y):
# Store both components on the instance
3 self.x = x
4 self.y = y
5
# __add__ is called for v1 + v2; other is the right-hand operand
6 def __add__(self, other):
# Return a new Vector; neither operand is modified
7 return Vector(self.x + other.x, self.y + other.y)
8
# __repr__ defines how the vector is displayed
9 def __repr__(self):
# Format it as Vector(x, y)
10 return f"Vector({self.x}, {self.y})"
11
# Create two vectors
12v1 = Vector(1, 2)
13v2 = Vector(3, 4)
# v1 + v2 calls v1.__add__(v2); prints Vector(4, 6)
14print(v1 + v2)

Output

Vector(4, 6)
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Python code and how often they appear.

  • _× 12
  • .× 8
  • (× 8
  • )× 8
  • ,× 7
  • :× 4
  • =× 4
  • +× 3
  • "× 2
  • {× 2

More Python examples at level 4

← Python typing practice