Python Properties · Exercises
Object-Oriented Python

Python Properties Exercises

4 exercises that build on the Python @property: Getters and Setters lesson, from easy to hard. Each one is checked in your browser when you press Check. Stuck? Use the hint before peeking at the solution.

What this lesson covers: A property is a method that Python lets you use like a plain attribute, so obj.price looks like simple data access while the class quietly computes the value or checks a new one before storing it. By the end you can turn a method into a read-only computed attribute with @property, add an @x.setter that validates and raises ValueError, keep the real value in a private _x attribute, avoid the RecursionError trap, and decide when a plain attribute is enough. You will practise: Add read-only properties; Predict the battery level; Fix the unchecked starting balance; Two views of one value.

0 / 4 completed

Python Properties practice exercises

1. Add read-only properties

Write code Easy

The class Rectangle stores width and height. Add two read-only properties: area (width times height) and perimeter (2 times width plus height). They are read without parentheses, for example room.area.

Your code
class Rectangle:
    def __init__(self, width, height):
        self.width = width
        self.height = height

    # add the area and perimeter properties here


room = Rectangle(4, 5)
print(room.width, room.height)

2. Predict the battery level

Predict the output Medium

The setter clamps every value into the range 0 to 100. Remember that phone.level -= 30 reads the property, subtracts, then assigns the result back through the setter. Type exactly what the program prints.

Read this code
class Battery:
    def __init__(self, level):
        self.level = level

    @property
    def level(self):
        return self._level

    @level.setter
    def level(self, value):
        self._level = max(0, min(100, value))

    @property
    def status(self):
        return "low" if self._level < 20 else "ok"

phone = Battery(150)
print(phone.level)
phone.level = 15
print(phone.level, phone.status)
phone.level -= 30
print(phone.level, phone.status)

3. Fix the unchecked starting balance

Fix the bug Medium

Account refuses negative balances through its setter, yet Account(-20) is accepted without complaint. The program should print Rejected: balance cannot be negative. Fix __init__ so the very first value is validated too.

Your code
class Account:
    def __init__(self, balance):
        self._balance = balance

    @property
    def balance(self):
        return self._balance

    @balance.setter
    def balance(self, value):
        if value < 0:
            raise ValueError("balance cannot be negative")
        self._balance = value

try:
    acct = Account(-20)
    print("Created with balance", acct.balance)
except ValueError as err:
    print("Rejected:", err)

4. Two views of one value

Write code Hard

Build a class Duration that keeps its length in seconds in the private attribute _seconds.

  • seconds is a property with a getter and a setter. The setter raises ValueError for a negative number. __init__(self, seconds) must use it, so the first value is checked too.
  • minutes is a second property. Its getter returns seconds / 60; its setter takes minutes, stores minutes * 60 seconds, and must also refuse negative numbers.

Nothing about minutes is stored: it is just another view of the same data.

Your code
class Duration:
    def __init__(self, seconds):
        pass

    # add the seconds and minutes properties here


clip = Duration(90)
print("created")

Next lessonPython Dunder (Magic) Methods

More Python @property: Getters and Setters examples · All Python exercises