Focused practice · 8 min read

Python Class Exercises: Build a Small Object Model

Classes become easier when you start with one small record. Build an object that stores a few fields, add one method, and test it before adding more behaviour.

Start with a blueprint

A class groups data and behaviour. __init__ runs when an object is created and assigns the initial attributes. Keep the first version small: two fields are enough to see the pattern.

class Order:
    def __init__(self, drink, price):
        self.drink = drink
        self.price = price

order = Order("latte", 4.5)
print(order.drink, order.price)

A two-field class

Add a method

A method is a function inside the class. Its first parameter is self, which refers to the current object. Call the method on an instance; do not pass self yourself.

class Order:
    def __init__(self, drink, price, quantity=1):
        self.drink = drink
        self.price = price
        self.quantity = quantity

    def total(self):
        return self.price * self.quantity

print(Order("latte", 4.5, 2).total())

A computed total

Keep instances independent

Each object has its own attributes. Creating a second Order does not overwrite the first. Put the objects in a list when you need to process several records with the same loop.

class Order:
    def __init__(self, drink, price):
        self.drink = drink
        self.price = price

orders = [Order("latte", 4.5), Order("tea", 3.0)]
for order in orders:
    print(order.drink, order.price)

Several independent objects

Use a method for a repeated calculation

If every caller would otherwise repeat the same formula, move it into a method. The method name documents the intent, and the calculation has one place to change.

class Order:
    def __init__(self, price, quantity):
        self.price = price
        self.quantity = quantity

    def total(self):
        return self.price * self.quantity

print(Order(4.5, 3).total())

One place for the formula

Know when a dictionary is enough

A class is not mandatory. If you only need to pass a fixed record around, a dictionary may be simpler. Introduce a class when behaviour and state belong together, or when the same operations keep repeating.

order = {"drink": "latte", "price": 4.5}
print(order["drink"])
print(order["price"] * 2)

A dictionary alternative

Your practice checklist

Common questions

What is self?

self is the instance the method was called on. Python passes it automatically, which is why callers do not provide it.

Do I need a class for every program?

No. Use a dictionary for a simple record and a function for a calculation. A class is useful when data and behaviour belong together.

Why do I get a missing argument error?

A method defined without self, or called without the required arguments, can produce this. Check the method signature and the call.

Practice classes

12 questions on __init__, self, attributes, methods, and independent instances.

Open practice

Keep reading: