ProgrammingHardProduct-company MCQ pattern

What is printed?

What is printed?
class C:
    n = 0
    def __init__(self):
        C.n += 1
    @classmethod
    def total(cls):
        return cls.n

class D(C):
    pass

D(); C(); D()
print(C.total(), D.total())
  1. A. 3 3
  2. B. 1 3
  3. C. 1 2
  4. D. 3 2

Correct answer: A. 3 3

C.n += 1 always updates the attribute on C itself, even when a D object is created. D has no n of its own, so cls.n for D finds C.n by inheritance. Both totals are 3.

More Python Programming questions

Exams that ask this topic