ProgrammingHardTCS NQT · Infosys
What does this Python code print? def deco(tag): def wrap(fn): def inner(x): return "<" + tag + ">" + fn(x) + "</" + tag + ">" return inner return wrap @deco("b") @deco("i") def show(x): return x print(show("hi"))
- A. <i><b>hi</b></i>
- B. <b>hi</b><i>hi</i>
- C. <b><i>hi</b></i>
- D. <b><i>hi</i></b>
Correct answer: D. <b><i>hi</i></b>
Decorators apply bottom-up: show = deco("b")(deco("i")(show)). The inner (i) wrapper wraps the original function, and the b wrapper wraps that result, so b is the outermost tag.
More Python Programming questions
- What does this Python code print? words = ["bb", "a", "ccc", "dd", "e", "fff"] print(sorted(words, key=len, reverse=True)[:3], min(words…
- What is printed? python def f(): for i in range(3): try: if i == 1: continue if i == 2: return 'ret' finally: print('f', i, end=' ')…
- What is printed? python class A: def f(self): return 'A' class B(A): def f(self): return 'B' + super().f() class C(A): def f(self): return…
- What is printed? python def gen(): x = yield 1 print('got', x) y = yield x 2 return y g = gen() print(next(g)) print(g.send(10)) try…
- What is printed? python funcs = [] for i in range(3): funcs.append(lambda x=i: x 10) funcs.append(lambda: i 10) print([f() for f in funcs])
- What is printed? python class Tag: items = [] n = 0 def add(self, v): self.items += [v] self.n += 1 a, b = Tag(), Tag() a.add('x')…