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)- A. ['A'] ['B', 'C'] a a c
- B. ['A', 'B', 'C'] [] a ? c
- C. ['A', 'B', 'C'] ['B', 'C'] a a c
- 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
- What is printed? python class CM: def init(self, name, swallow): self.name, self.swallow = name, swallow def enter(self): print("in" +…
- What is printed? python import bisect a = [1, 3, 3, 3, 7] i, j = bisect.bisectleft(a, 3), bisect.bisectright(a, 3) bisect.insortleft(a…
- What is printed? python from itertools import groupby s = "aabbbaac" g1 = [(k, len(list(v))) for k, v in groupby(s)] g2 = {k: len(list(v))…
- What is printed? python print("abc" 2 + "d", len("abc" 0))
- What is printed? python x = [10, 20, 30, 40, 50] print(x[-1], x[len(x) // 2], x[-2:])
- What is printed? python s = "Python" print(s.find("th"), s.find("z"), s.upper()[1:3])