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)- A. N.add N.add N.radd N.add
- B. S.radd N.add N.radd N.add
- C. S.radd S.radd N.radd N.add
- 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
- What is printed? python class C: k = 5 def f(self, v=k): return v def g(self): try: return k except NameError: return "NE" C.k = 9…
- What is printed? python d = {"a": 1} print(d.get("b", 0), "a" in d, 1 in d, d.get("b"))
- What is printed? python print(list("ab") + ["c"], tuple([1, 2]) 2)
- What is printed? python d = {"a": 1} try: d["k"] except KeyError as e: print(repr(e), e.args, len(d))
- What is printed? python print([x if x % 2 else -x for x in range(5)], [x for x in range(5) if x % 2 or x == 0])
- What is printed? python print(int(" -0012 "), int("1000"), float("1e3"), int("101", 2), int(-2.9))