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 methods1class Vector: # Initialize with x and y coordinates2 def __init__(self, x, y): # Tuple unpacking to assign x and y3 self.x, self.y = x, y # __add__ is called when using + operator4 def __add__(self, other): # Return new Vector with added coordinates5 return Vector(self.x + other.x, self.y + other.y) # __repr__ returns string representation6 def __repr__(self): # Return formatted string showing coordinates7 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. 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