All lessons

Leveling up · step 20 of 22

Classes & objects

12 minDesign your own type, with data and behaviour together.

A blueprint for your own type

A class describes the data and the behaviour of something. An object built from it is an instance.

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

    def speak(self):
        return f"{self.name} says woof"

rex = Dog("Rex", 3)      # create an instance
print(rex.name)          # Rex
print(rex.speak())       # Rex says woof

What is self?

self is the instance the method is working on — Python passes it in for you. __init__ is the setup that runs when an object is created, and it is where attributes are stored (self.name = name).

Methods are just functions that live inside a class, and every method's first parameter is self. Two separate objects each keep their own attributes:

a = Dog("Ada", 3)
b = Dog("Pixel", 1)
print(a.name)   # Ada
print(b.name)   # Pixel

Classes are how you keep data and the operations on that data together — the shape most real Python code is built from.

Remember this

  • A class is a blueprint; an instance is one object made from it
  • __init__ sets up attributes when an object is created
  • self is the object the method works on

Quick quiz

Three questions. 3 correct answers and you have the idea — you can retry as often as you like.

  1. 1. What runs when you create Dog("Rex", 3)?

  2. 2. What does self refer to?

  3. 3. How do you read the name of the object rex?

Answer all three to check them.

Now write it yourself

0/2 passed
1

Practice 1

Write a class `Cat` with `__init__(self, name)` that stores the name, and a method `speak()` that returns `<name> says meow`.

practice_1.py
2

Practice 2

Write a class `Rectangle` with `__init__(self, width, height)` and a method `area()` that returns width multiplied by height.

practice_2.py

Finish with two of three quiz answers correct and every exercise passing, and this lesson is marked complete.