ProgrammingHardProduct-company MCQ pattern

What is printed?

What is printed?
class Vec:
    def __init__(self, x, y):
        self.x, self.y = x, y
    def __radd__(self, o):
        return Vec(self.x + o, self.y + o)
    def __repr__(self):
        return f"Vec({self.x},{self.y})"
print(5 + Vec(1, 2))
  1. A. TypeError
  2. B. Vec(6,7)
  3. C. Vec(5,5)
  4. D. 6

Correct answer: B. Vec(6,7)

int.__add__(5, Vec(...)) returns NotImplemented since int doesn't know how to add a Vec, so Python falls back to Vec.__radd__(vec, 5), adding 5 to each coordinate: Vec(6, 7).

More Python Programming questions

Exams that ask this topic