Classes and objects

Classes & Objects, lesson 1 of 6

🏗️ Classes & Objects, lesson 1 of 6

Classes and objects

Create your own types that bundle data together.

9 min

1 exercise

2 quizzes

0/3 solved

Getting Python ready… examples can run in a moment.

You've used built-in types like str, list and dict. A class lets you define your own type. Think of it as a blueprint: each object (also called an instance) built from it carries its own data.

class Dog:
    def __init__(self, name, age):
        self.name = name
        self.age = age
  • __init__ runs automatically when you create an object. It sets up the object's attributes.
  • self is the object being built; self.name = name stores the value on it.
Example

Your first class

Each object keeps its own name and age. Create a third dog and print its name.

Quiz

What does this print?

Attributes are variables attached to an object. Read them with a dot (rex.age) and change them by assigning (rex.age += 1). __init__ can take default values like any function.

By convention class names use CapWords, while functions and attributes use snake_case.

Example

Defaults and changing attributes

Each player gets a fresh empty inventory list, because it's created inside __init__. Give the boss a "club" too.

Example

Forgetting self

Change the line to self.name = name and run it again.

Quiz

Inside a class, what does self refer to?

Exercise

A Book class

  1. Finish Book.__init__ so it stores title, author and pages as attributes, plus a read attribute that starts as False.
  2. Create my_book for Dune by Frank Herbert, 412 pages.