Magic Methods in Python

Level 4246 keystrokes

This implements magic methods for operator overloading. __add__ enables + operator and __repr__ defines string representation.

Python code

# Define a Vector class with magic methods
1class Vector:
# Initialize with x and y coordinates
2 def __init__(self, x, y):
# Tuple unpacking to assign x and y
3 self.x, self.y = x, y
# __add__ is called when using + operator
4 def __add__(self, other):
# Return new Vector with added coordinates
5 return Vector(self.x + other.x, self.y + other.y)
# __repr__ returns string representation
6 def __repr__(self):
# Return formatted string showing coordinates
7 return f"Vector({self.x}, {self.y})"
8
# Create first vector (1, 2)
9v1 = Vector(1, 2)
# Create second vector (3, 4)
10v2 = Vector(3, 4)
# Add vectors using + operator, prints Vector(4, 6)
11print(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
  • ,× 9
  • .× 8
  • (× 8
  • )× 8
  • :× 4
  • +× 3
  • =× 3
  • "× 2
  • {× 2

More Python examples at level 4

← Python typing practice