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 class1class Vector: # The constructor takes the x and y components2 def __init__(self, x, y): # Store both components on the instance3 self.x = x4 self.y = y5 # __add__ is called for v1 + v2; other is the right-hand operand6 def __add__(self, other): # Return a new Vector; neither operand is modified7 return Vector(self.x + other.x, self.y + other.y)8 # __repr__ defines how the vector is displayed9 def __repr__(self): # Format it as Vector(x, y)10 return f"Vector({self.x}, {self.y})"11 # Create two vectors12v1 = 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. 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