Skip to content
Foxipa
Code Completion 6 Challenges

Complete the Python Properties Code

Practice building managed attributes and using functools.cached_property for reusable per-instance values.

~10 min read

Challenge 1

Turn label into a read-only property that returns the stored _label value.

python Your answer
class Item:
    def __init__(self, label):
        self._label = label

    

item = Item("Book")
print(item.label)

Press Ctrl⌘Enter to check your answer

Challenge 2

Make score writable through a property and reject negative scores.

python Your answer
class Player:
    def __init__(self, score):
        self._score = score

    @property
    def score(self):
        return self._score

    

player = Player(10)
player.score = 25
print(player.score)

Press Ctrl⌘Enter to check your answer

Challenge 3

Add a deleter that resets the stored token when del session.token is used.

python Your answer
class Session:
    def __init__(self, token):
        self._token = token

    @property
    def token(self):
        return self._token

    

session = Session("abc")
del session.token
print(session.token)

Press Ctrl⌘Enter to check your answer

Challenge 4

Complete the setter so assignments convert values to integers while using the existing property name.

python Your answer
class Counter:
    def __init__(self, value):
        self._value = value

    @property
    def value(self):
        return self._value

    

counter = Counter(4)
counter.value = "9"
print(counter.value)

Press Ctrl⌘Enter to check your answer

Challenge 5

Make mean calculate once per Series instance by using the standard library's cached property decorator.

python Your answer
from functools import cached_property

class Series:
    def __init__(self, values):
        self.values = tuple(values)

    
    def mean(self):
        return sum(self.values) / len(self.values)

series = Series([2, 4, 6])
print(series.mean)

Press Ctrl⌘Enter to check your answer

Challenge 6

Remove the old cached count so the next lookup uses the updated list.

python Your answer
from functools import cached_property

class Basket:
    def __init__(self, items):
        self.items = list(items)
        self.calculations = 0

    @cached_property
    def count(self):
        self.calculations += 1
        return len(self.items)

basket = Basket(["pen"])
print(basket.count)
basket.items.append("book")

print(basket.count)
print(basket.calculations)

Press Ctrl⌘Enter to check your answer