Python, properly · Chapter 24 of 42

Properties and validation

By the end of this chapter you can make an attribute check every value it is given, compute an attribute when it is read, and choose between data that belongs to one object and data shared by the whole class. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.

  • Part: Objects
  • 4 tasks
  • Python
  • In the all labs plan

The first 2 chapters of Python, properly are free. This one comes with the all labs plan.

Why you need this

Rafiq found a dish priced at -40 rupees in last week's bills, and a rider with no area at all. A class from chapter 23 stores whatever it is handed, and anyone can change an attribute later:

class Rider:
    def __init__(self, rider_id, area):
        self.rider_id = rider_id
        self.area = area


r = Rider("R9", "Andheri")
r.area = ""
print(vars(r))
{'rider_id': 'R9', 'area': ''}

A check in __init__ would stop a bad rider from being made, but not r.area = "" a hundred lines later. And a set_area() method only helps if everyone remembers to call it instead of assigning. You need the plain r.area = ... itself to run your check.

What you build: 4 tasks

Each task has tests. You write the code in the lab's editor and press Check.

  1. Task 1

    dish.py: a Dish that refuses a bad price

    Write a class Dish. Dish(name, price) keeps name with the spaces around it removed, and raises ValueError when the name is empty after that.

    price is a property with a setter: a price of 0 or less raises ValueError, both when the dish is made and whenever price is changed later, and a refused change keeps the old price.

    The check makes Dish(" Veg Pulao ", 160) (name "Veg Pulao"), sets its price to 175 and then -1, and tries Dish("Roti", 0), Dish("Roti", -15) and Dish(" ", 15).

  2. Task 2

    bill.py: a Bill with GST worked out, not stored

    Write a class Bill with a class attribute GST_RATE = 0.05. Bill(subtotal) keeps subtotal. Two read-only properties: gst is subtotal times the class's GST_RATE rounded to 2 decimal places, and total is subtotal plus gst.

    Bill(240) has gst 12.0 and total 252.0; Bill(199) has gst 9.95. Assigning b.total or b.gst raises AttributeError. After Bill.GST_RATE = 0.12, the same Bill(240) gives gst 28.8: the rate is read from the class every time.

  3. Task 3

    rider.py: count every rider, keep each one's deliveries

    Write a class Rider. Rider(rider_id, name) keeps both, plus deliveries, an empty list for each new rider. deliver(order_id) adds the order id to that rider's list.

    Rider.count is a class attribute that starts at 0, and every new Rider adds 1 to it. The check makes two riders and expects Rider.count to go up by 2, no rider to have its own count attribute, and deliveries to one rider never to show up in another's list.

  4. Task 4 · interview question

    Interview: phone.py, a phone number that cleans itself

    Write a class Customer. Customer(name, phone) keeps name and phone, and phone is a property whose setter stores it clean: keep only the digits; 12 digits starting with 91 lose the 91, 11 digits starting with 0 lose the 0; anything that is not then exactly 10 digits raises ValueError, and a refused change keeps the old phone.

    "+91 84641 29694" becomes "8464129694", "83262-72722" becomes "8326272722", "07089496252" becomes "7089496252", and "12345" raises ValueError. The check also cleans every phone in /workspace/data/customers.csv and changes a customer's phone after it is made.

What you will learn

  • @property: an attribute that runs a method when it is read.
  • Setters: run a check, and refuse with ValueError, whenever the attribute is assigned.
  • Read-only and computed attributes: worked out each time, never stale.
  • Class attributes: one value shared by every object, and how an assignment through an object hides it.

More in Objects

Build "Properties and validation" yourself

DabbaDrop, a Mumbai tiffin startup, runs on Excel and WhatsApp. You are its first Python developer. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.

The first 2 chapters of Python, properly are free. This one comes with the all labs plan.