Privacy note: We capture your IP address to provide customised and focused services. See our Privacy Policy.

Advanced Python & Software Engineering — Alpha School

Lesson 1: Classes and Instances — Your First Objects

So far you have probably written Python as a list of instructions: read some input, loop over it, print a result. That style works well for short scripts, but as programs grow it starts to hurt. Data ends up scattered across variables, functions take long lists of arguments, and a small change in one place breaks something somewhere else. Object-oriented programming is Python's answer to that problem. It lets you bundle data together with the functions that work on that data, into a single thing called an object.

A class is the blueprint for objects of one kind, and an instance is one object built from that blueprint. Think of a class as a recipe and instances as the dishes cooked from it: every dish follows the same recipe, but each one has its own ingredients. In code, you define a class with the class keyword, and you create instances by calling the class as if it were a function. The special method __init__ runs automatically when an instance is created, and its job is to set up the instance's starting state.

Inside a class, functions are called methods, and they always receive the instance itself as their first argument, conventionally named self. That is how a method knows which object it is working on. Attributes set on self inside __init__ belong to that one instance, so two objects made from the same class can hold different values. The example below defines a BankAccount: each account tracks its own balance, and the deposit and withdraw methods change only the account they are called on.

class BankAccount:
    def __init__(self, owner, balance=0):
        self.owner = owner
        self.balance = balance

    def deposit(self, amount):
        if amount <= 0:
            raise ValueError("deposit must be positive")
        self.balance += amount

    def withdraw(self, amount):
        if amount > self.balance:
            raise ValueError("insufficient funds")
        self.balance -= amount
        return amount


ana = BankAccount("Ana", 100)
ben = BankAccount("Ben", 50)
ana.deposit(25)
print(ana.balance)  # 125
print(ben.balance)  # 50 — Ben's account is untouched

Why bundle data and behaviour together?

The payoff is that the rules for your data live in exactly one place. In the example, the rule that a balance can never go negative lives inside withdraw. No other part of the program needs to remember it, and no other part can accidentally break it by subtracting directly — well, almost: Python does not lock attributes away, so nothing stops another piece of code from writing ana.balance = -999. The protection here is by convention, not by force, and that is a deliberate part of Python's design. The language trusts you, and in return it stays simple. Later lessons will show the tools Python does offer for guarding attributes, such as properties.

A good habit to build now is to ask, for every new piece of data in a program, whether it belongs to an object. If a group of variables always travels together — a student's name, grade list and average, or a rectangle's width, height and area — that is a class waiting to be written. Start small: one class, a clear __init__, and a few methods that do one thing each. The rest of this unit builds on exactly that foundation, adding inheritance, special methods and class-level tools one step at a time.

Going further

Two details about __init__ are worth knowing early. First, it never returns a value: its job is to set up the new object, and Python itself returns the object to the caller. Second, you can give its parameters default values, as the example does with balance=0, which makes some arguments optional. A class with sensible defaults is much friendlier to use, because callers only pass what is different. The same idea applies to methods: a method that takes an optional argument with a default is easier to call correctly than one that demands every value up front.

Python also gives you tools to inspect your own objects. The built-in dir() lists everything an object can do — its attributes and methods — and help() shows the documentation for a class. When you are learning, running dir(ana) in the interactive prompt is a quick way to check what you have built. And remember that a method is just a function that lives in a class: BankAccount.deposit is a function, and ana.deposit is that same function bound to the instance ana. That binding is what self is really about.

Try a small exercise to make the idea stick: model a Playlist of your own, with a name and a list of songs, a method to add a song, and a method that returns the total playing time if each song stores its length in seconds. Then create two playlists and add different songs to each. If the songs stay separate — if adding a song to one playlist does not change the other — you have understood instance attributes. If they leak across, check whether you accidentally used a class-level list. That single mistake, a mutable class attribute shared by all instances, is one of the most common object-oriented bugs in Python, and this exercise will teach you to spot it forever.

Key Terms

Class
A blueprint that defines the data (attributes) and behaviour (methods) shared by all objects of one kind.
Instance (object)
One concrete object created from a class, with its own attribute values.
Method
A function defined inside a class, called on an instance of that class.
__init__
The special method Python calls automatically when an instance is created, used to set up its initial state.
self
The conventional name for the first parameter of a method: the instance the method was called on.
Attribute
A piece of data stored on an object, accessed with dot notation such as ana.balance.
Encapsulation
Bundling data together with the methods that operate on it, so the rules for that data live in one place.

Discussion Questions

  1. Why is it useful that ana and ben can be created from the same class but hold different balances? What would go wrong if balance were shared?
  2. Python lets any code write ana.balance = -999 directly. Is that a weakness of the language, or a reasonable trade-off? When might you want a guard?
  3. Think of something in your own life that could be modelled as a class — a playlist, a recipe book, a sports team. What attributes and methods would it have?

Practice Questions

  1. Write a class Rectangle with __init__(self, width, height) and methods area() and perimeter().
  2. What does self refer to inside a method?
  3. Create two instances of your Rectangle class with different sizes. Do they share their width and height?
  4. What happens if you call BankAccount("Ana") without a balance?
  5. Why does deposit raise a ValueError for a zero or negative amount?
Show answers
  1. def area(self): return self.width * self.height and def perimeter(self): return 2 * (self.width + self.height). Store width and height on self in __init__, then compute from them in each method.
  2. The instance the method was called on. When you write ana.deposit(25), Python passes ana as the self argument automatically.
  3. No — each instance keeps its own attribute values. Attributes set on self belong to that one instance, so changing one rectangle never affects the other.
  4. The balance defaults to 0. The __init__ signature gives balance a default value of 0, so it may be left out.
  5. To enforce the rule that a deposit must add money, in one place. The check lives inside the method, so every caller gets the same behaviour without repeating the test.
Keep reading to complete this lesson