Bird
0
0

You want to create a class Vector that supports adding vectors and multiplying by a number. Which methods should you define to support v1 + v2 and v1 * 3 where v1 and v2 are Vector objects?

hard📝 Application Q15 of 15
Python - Magic Methods and Operator Overloading
You want to create a class Vector that supports adding vectors and multiplying by a number. Which methods should you define to support v1 + v2 and v1 * 3 where v1 and v2 are Vector objects?
A__add__ for vector + vector, __rmul__ for number * vector
B__add__ for vector + vector, __mul__ for vector * number
C__add__ for vector + vector, __mul__ for number * vector
D__radd__ for vector + vector, __mul__ for vector * number
Step-by-Step Solution
Solution:
  1. Step 1: Identify method for vector + vector

    __add__ handles adding two Vector objects like v1 + v2.
  2. Step 2: Identify method for vector * number

    __mul__ handles multiplying Vector by a number like v1 * 3.
  3. Final Answer:

    __add__ for vector + vector, __mul__ for vector * number -> Option B
  4. Quick Check:

    Use __add__ and __mul__ for these operations [OK]
Quick Trick: Use __add__ for +, __mul__ for * with your class [OK]
Common Mistakes:
  • Confusing __rmul__ with __mul__
  • Using __radd__ instead of __add__ for vector + vector
  • Assuming number * vector uses __mul__ (it uses __rmul__)

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes