CS FundamentalsVery hardGATE CS · Software Engineering · Advanced

What is printed?

What is printed?
class Cfg:
    _inst = None
    def __new__(cls, *args):
        if cls._inst is None:
            cls._inst = super().__new__(cls)
        return cls._inst
    def __init__(self, v):
        self.v = v
a = Cfg(1)
b = Cfg(2)
print(a is b, a.v, b.v)
  1. A. True 1 1
  2. B. True 2 2
  3. C. False 1 2
  4. D. True 1 2

Correct answer: B. True 2 2

__new__ returns the same instance both times, but Python still calls __init__ on it for every Cfg(...) call, so the second call overwrites v with 2 for both names. A singleton that must keep its first state has to guard __init__ as well.

More Software Engineering, Git and Cloud Basics questions

Exams that ask this topic