Object-oriented programming · 23 / 26 Exercise Medium

Vectors with operators

Objective

With special methods (__add__, __sub__, __eq__…) your objects can use Python operators as if they were numbers.

Instructions

  • Define the class Vector with attributes x and y and the methods __add__ (addition), __sub__ (subtraction), __mul__ (multiply by a number), __eq__ (equality), __abs__ (length, with math.hypot) and __str__ (text (x, y)).
  • Read two lines with x and y of two vectors a and b, and then an integer k.
  • Show a + b = ..., a - b = ..., a * k = ..., |a| = ... (two decimals) and a == b: ....
Input
3 4
1 2
2
Output
a + b = (4, 6)
a - b = (2, 2)
a * k = (6, 8)
|a| = 5.00
a == b: False

Open the editor in full screen: the statement on the left and your code, the output and the tests on the right.

Start exercise