ProgrammingVery hardProduct company OA
What is printed?
What is printed?
def tag(t):
print("make", t, end=" ")
def deco(fn):
print("wrap", t, end=" ")
def inner(*a):
return f"<{t}>" + fn(*a) + f"</{t}>"
return inner
return deco
@tag("b")
@tag("i")
def hi(n): return "x" * n
print(hi(2), hi.__name__)- A. make i wrap i make b wrap b <b><i>xx</i></b> inner
- B. make b make i wrap i wrap b <b><i>xx</i></b> inner
- C. make b make i wrap b wrap i <i><b>xx</b></i> inner
- D. make b make i wrap i wrap b <b><i>xx</i></b> hi
Correct answer: B. make b make i wrap i wrap b <b><i>xx</i></b> inner
The decorator EXPRESSIONS are evaluated top to bottom (make b, make i), but the resulting decorators are APPLIED bottom to top: hi = tag('b')(tag('i')(hi)), so 'wrap i' prints before 'wrap b' and the outermost tag is <b>. Without functools.wraps the name of the replacement function is 'inner'. Output: make b make i wrap i wrap b <b><i>xx</i></b> inner.
More Python Programming questions
- What is printed? python x = 1 class K: x = 2 a = [x for in range(2)] b = [x i for i in range(x + 1)] def m(self): return x print(K.a, K.b…
- What is printed? python data = [5, 3, 8, 1] out = [] while (n := len(data)) > 1: first, data = data data[-1] += first out.append((n…
- What is printed? python from functools import lrucache @lrucache(maxsize=None) def path(n): return [0] if n == 0 else path(n - 1) + [n] p…
- What is printed? python class Seq: def init(self, n): self.n = n; self.calls = 0 def getitem(self, i): self.calls += 1 if i >= self.n…
- What is printed? python import heapq tasks = [(2, "write"), (1, "test"), (2, "ship"), (1, "plan")] h = [] for i, (p, name) in…
- What is printed? python x = -13 print(x >> 2, x // 4, ~x, x & 0xF, bin(x & 0xFF).count("1"), (-x) >> 2)