v9.1.1
Menu

Magic Methods

mediumFREEClasses & ObjectsPython OOPPython Foundations

Problem Statement

Implement a Vector class with magic methods for arithmetic operations.

Background

Python magic methods enable operator overloading:

  • add: + operator
  • sub: - operator
  • mul: * operator (scalar)
  • eq: == operator
  • len: len() function

Your Task

Create a Vector class that supports:

  • Addition: v1 + v2 (element-wise)
  • Subtraction: v1 - v2 (element-wise)
  • Scalar multiplication: v * scalar
  • Equality: v1 == v2
  • Length: len(v) returns number of elements
  • str: "Vector([...])"

Example

Input
Vector([1, 2, 3]) + Vector([4, 5, 6])
Output
Vector([5, 7, 9])
Reasoning
  • Inputs: two Vector objects, each holding three numbers: u=(1,2,3)\mathbf{u} = (1, 2, 3) and v=(4,5,6)\mathbf{v} = (4, 5, 6). Writing a plus sign between them asks your class what "adding two vectors" means.
  • Math: vector addition is element-wise, so component ii of the result is ui+viu_i + v_i:
    • u1+v1=1+4=5u_1 + v_1 = 1 + 4 = 5
    • u2+v2=2+5=7u_2 + v_2 = 2 + 5 = 7
    • u3+v3=3+6=9u_3 + v_3 = 3 + 6 = 9
  • Output: a brand-new Vector holding (5,7,9)(5, 7, 9). When printed, it appears as Vector([5, 7, 9]): the word Vector wrapping the bracketed list of components.
  • Both originals stay unchanged: u\mathbf{u} still prints as Vector([1, 2, 3]) afterwards. The result has the same length as its inputs, 3 here.
  • Scalar multiplication follows the same component-by-component idea: 2u=(2,4,6)2\mathbf{u} = (2, 4, 6), matching the second example in the description.

Constraints

  • Vectors for arithmetic must have same length
  • Return new Vector objects, don't modify originals

Learn this in

More from Python Foundations

solution.py

Test results

Sign in to run your code against the test cases.