ProgrammingVery hardProduct company OA

What is printed?

What is printed?
class Base:
    registry = []
    def __init_subclass__(cls, **kw):
        cls.registry.append(cls.__name__)
        cls.tag = kw.get("tag", getattr(cls, "tag", "?"))
class A(Base, tag="a"): pass
class B(A): registry = []
class C(B, tag="c"): pass
print(Base.registry, B.registry, A.tag, B.tag, C.tag)
  1. A. ['A'] ['B', 'C'] a a c
  2. B. ['A', 'B', 'C'] [] a ? c
  3. C. ['A', 'B', 'C'] ['B', 'C'] a a c
  4. D. ['A'] ['B', 'C'] a ? c

Correct answer: A. ['A'] ['B', 'C'] a a c

__init_subclass__ runs on the parent each time a subclass is created, after the subclass body has executed. A has no registry of its own, so cls.registry resolves to Base's list → ['A']. B's body defines a fresh list, which shadows Base's; 'B' is appended to that new list, and C (looking up through B) appends there too → ['B', 'C']. B gets no tag keyword, but getattr(cls, 'tag') finds the inherited 'a'; C is given 'c'. The '?' options forget attribute inheritance.

More Python Programming questions

Exams that ask this topic