Classes and objects

Topic 1 of 4 in Classes and objects7 min readBeginnerFree course

Overview

You’ve used plenty of objects already: strings have .upper(), lists have .append(), files have .read(). Each is an object of some type (or class) that bundles data with behaviour. Now you’ll create your own types. Classes are how larger programs model the things they deal with: users, orders, accounts, game characters.

Why classes?

Suppose you track dogs with dictionaries and functions:

Python
rex = {"name": "Rex", "age": 3}

def describe(dog):
    return f"{dog['name']} is {dog['age']}"

It works, but nothing connects the functions to the data they expect, typos in keys only show up at run time, and every function has to be passed the dict. A class packages the data and the functions that operate on it into one unit.

Defining a class

A class is a blueprint; objects are built from it. class Dog: defines def init(self, name, age): self.name = name and self.age = age, and def speak(self): return f”{self.name}: Woof!“. dog1 = Dog(“Rex”, 3) is an object with name = “Rex” and age = 3; dog2 = Dog(“Bella”, 7) is another object with name = “Bella” and age = 7. Each object (instance) has its own data. Methods are shared; self is the object the method was called on.

Python
class Dog:
    """A dog with a name and an age."""

    def __init__(self, name, age):
        self.name = name
        self.age = age

    def speak(self):
        return f"{self.name}: Woof!"

    def birthday(self):
        self.age += 1
  • class Dog: starts the definition. Class names use CapWords (Dog, TodoList, BankAccount).
  • Functions inside a class are methods.
  • __init__ is a special method that Python calls automatically to set up each new object.

Creating objects

Call the class like a function to create an instance:

Python
rex = Dog("Rex", 3)
bella = Dog("Bella", 7)

print(rex.name)          # Rex
print(bella.speak())     # Bella: Woof!
rex.birthday()
print(rex.age)           # 4
print(bella.age)         # 7 — bella is unaffected

Dog("Rex", 3) creates a new, empty object, then calls __init__(that_object, "Rex", 3). Each object stores its own data.

self

Every method’s first parameter is self: the particular object the method was called on. When you write rex.speak(), Python effectively calls Dog.speak(rex) — so inside speak, self is rex.

  • self.name = name in __init__ creates an attribute on that object.
  • self.age += 1 in birthday changes the age of whichever dog it was called on.

Forgetting self is the classic beginner mistake:

Python
class Dog:
    def speak():                      # missing self
        return "Woof"

Dog().speak()
Text
TypeError: Dog.speak() takes 0 positional arguments but 1 was given

The “1 given” is the object itself, passed automatically.

Attributes

Attributes are read and set with a dot:

Python
rex.age = 5             # change it from outside
rex.owner = "Asha"      # you CAN add new attributes like this — but don't

Define all attributes in __init__, so every object has the same shape and readers can see the full list in one place. Use None or an empty collection for things that start unknown or empty:

Python
def __init__(self, owner):
    self.owner = owner
    self.tasks = []          # each object gets its own new list

Private by convention

Python has no truly private attributes. A leading underscore — self._balance — signals “internal: please don’t touch from outside”. Other programmers respect it; Python doesn’t enforce it.

Class attributes

A variable assigned in the class body (not on self) is shared by all instances:

Python
class Dog:
    species = "Canis familiaris"    # same for every dog

    def __init__(self, name):
        self.name = name            # different for every dog

Dog.species              # 'Canis familiaris'
Dog("Rex").species       # 'Canis familiaris'

Use class attributes for constants. Don’t use a mutable class attribute like tasks = [] for per-object data — it would be shared, just like the mutable default trap in Parameters and arguments.

Methods that keep objects valid

Methods are the place to enforce rules about the data:

Python
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

If all changes go through deposit and withdraw, the balance can never become negative.

Printing objects

Python
print(rex)        # <__main__.Dog object at 0x7f…>

Not very helpful! The next lesson, Special methods, shows how to give objects readable text — and how to make them work with ==, <, len() and more.

When to write a class

  • You have data and functions that always go together (an account and its deposit/withdraw).
  • You need many objects of the same shape (players, products, orders).
  • The thing has state that changes over time (a game character’s health).

For a few lines of logic, plain functions are simpler. For records that mostly hold data, Dataclasses saves a lot of typing.

Remember: the class is the blueprint, objects are built from it, __init__ sets up each object, and self is the object a method is working on.

Exercise

A to-do list class

Write a TodoList class. __init__(self, owner) stores the owner and starts with an empty list of tasks. Each task is a dict with title and done. Add methods: add(title) appends a task that isn’t done; complete(title) marks the matching task done and raises ValueError if there’s no such task; pending() returns the titles not yet done; summary() returns a string like Asha: 1 of 3 done. Create two lists for two people, add and complete some tasks, and print summaries and pending tasks to show that each object keeps its own data.

Python
class TodoList:
    def __init__(self, owner):
        ...

    def add(self, title):
        ...

    def complete(self, title):
        ...

    def pending(self):
        ...

    def summary(self):
        ...

Summary

  • A class is a blueprint for a new type; calling it — Dog("Rex", 3) — creates an object (an instance).
  • __init__ sets up each new object; it stores data in attributes such as self.name.
  • Methods are functions defined in the class; their first parameter, self, is the object they were called on.
  • Each object has its own attribute values, while methods are shared by all objects of the class.
  • Use classes to keep related data and the functions that work on it together.