Scale a Vector with Multiplication
Intermediate · Write the code · from Python Operator Overloading: Make Classes Work with +, -, ==
From the lesson: Python Operator Overloading: Make Classes Work with +, -, ==
The + operator means different things in different contexts. 3 + 5 gives you 8. 'hello' + ' world' gives you 'hello world'. [1, 2] + [3, 4] gives you [1, 2, 3, 4]. Same symbol, completely different behavior.
Read the lessonCreate a Vector class with x and y. Add __mul__ so vector * number scales both components. Add __rmul__ so number * vector also works. Add __repr__ returning 'Vector(<x>, <y>)'. Print Vector(3, 4) * 2 and 3 * Vector(1, 5).
# Create the Vector class with __mul__ and __rmul__
More Operator Overloading exercises
- Add Two Points TogetherBeginner
- Fix the Broken __iadd__Intermediate
- Predict the Operator OutputIntermediate
- Build a Fraction ClassAdvanced
- Refactor Methods to OperatorsAdvanced
All Python exercises · 50 practice problems · Object-Oriented Programming quiz