ProgrammingVery hardPython · GATE DA · Advanced

What is printed?

What is printed?
class A:
    def __new__(cls, v):
        print('new', v)
        return super().__new__(B) if v else super().__new__(cls)
    def __init__(self, v):
        print('init', v)
class B: pass
a = A(1)
b = A(0)
print(type(a).__name__, type(b).__name__)
  1. A. new 1 / new 0 / init 0 / A A
  2. B. new 1 / new 0 / init 0 / B A
  3. C. new 1 / init 1 / new 0 / init 0 / B A
  4. D. new 1 / init 1 / new 0 / init 0 / A A

Correct answer: B. new 1 / new 0 / init 0 / B A

__init__ is called only if __new__ returns an instance of the class (A); the B instance returned for v=1 skips __init__.

More Python Programming questions

Exams that ask this topic