ProgrammingVery hardProduct company OA

What is printed?

What is printed?
class N:
    def __add__(self, o): return "N.add"
    def __radd__(self, o): return "N.radd"
class S(N):
    def __radd__(self, o): return "S.radd"

print(N() + S(), S() + N(), 1 + N(), N() + 1)
  1. A. N.add N.add N.radd N.add
  2. B. S.radd N.add N.radd N.add
  3. C. S.radd S.radd N.radd N.add
  4. D. N.add N.add N.add N.add

Correct answer: B. S.radd N.add N.radd N.add

Normally x + y tries x.__add__ first. The exception: if y's type is a subclass of x's type and provides its own __radd__, the reflected method is tried first — so N() + S() gives 'S.radd'. S() + N() uses S's inherited __add__. 1 + N(): int.__add__ returns NotImplemented for N, so N.__radd__ runs. N() + 1 is plain N.__add__.

More Python Programming questions

Exams that ask this topic