ProgrammingHardGATE CS · Product-company placement
What is printed?
What is printed?
class Lazy:
def __init__(self): self.calls = 0
@property
def value(self):
self.calls += 1
return 42
from functools import cached_property
class Cached:
def __init__(self): self.calls = 0
@cached_property
def value(self):
self.calls += 1
return 42
a, b = Lazy(), Cached()
for _ in range(3):
a.value; b.value
print(a.calls, b.calls, "value" in vars(b))- A. 3 3 False
- B. 3 1 True
- C. 1 1 True
- D. 3 1 False
Correct answer: B. 3 1 True
A property recomputes on every access. cached_property computes once and stores the result in the instance __dict__ under the same name, which then shadows the (non-data) descriptor.
More Python Programming questions
- What is printed? python class Pos: def setname(self, owner, name): self.name = "" + name def get(self, obj, typ=None): return getattr(obj…
- What is printed? python def f(n): return [i for i in range(n) if i % 3 == 0 if i % 2 == 0] g = lambda n: [i for i in range(n) if i % 3 ==…
- What is printed? python a = {"x": 1, "y": 2} b = {v: k for k, v in a.items()} c = {k: v for k, v in zip("abc", [1, 2])} print(b, c, {1…
- What is printed? python a = b = [] a.append(1) c, d = [], [] c.append(1) x = y = 5 x += 1 print(b, d, y)
- What is printed? python a = [1, 2, 3] i = 0 i, a[i] = 2, 9 print(a, i)
- What is printed? python x = [0, 1] i = 0 x[i], i = 5, 1 j = 1 j, x[j] = 0, 7 print(x, i, j)