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))
  1. A. 3 3 False
  2. B. 3 1 True
  3. C. 1 1 True
  4. 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

Exams that ask this topic