Skip to contentSkip to navigation

Module 10 · Lesson 01

Classes and Objects

Build your own types: define a class, create objects from it, give them attributes and methods, and see why bundling data with behaviour keeps programs tidy.

  • About 8 minutes
  • Builds on earlier lessons
  • 12-question quiz at the end

What you will learn

  • Blueprint and objects
  • Methods and self
  • Keep data and rules together
  • Watch a plant grow

Your own kinds of value

A class is a blueprint. Each object made from it keeps its own data and knows its own actions.

  • class

    class Dog: starts a blueprint. By habit, class names start with a capital letter.

  • Objects

    rex = Dog("Rex", 3) builds one object. Call the class again for another.

  • Attributes

    self.name = name stores data on the object. Read it back with rex.name.

  • Methods

    A def inside the class is a method: rex.bark() runs it for rex.

Objects everywhere

You have used objects all along: every string and every list is one.

  • Game charactersEach enemy has its own health and its own attack() method.
  • Shopping cartsA cart holds its items and knows how to add up the total.
  • Music playersA song knows its title and length; a player knows what plays next.
  • Pet appsEach pet has a name, an age and a feed() method that changes how hungry it is.

Making an object

This line builds a new object from a class. Tap each part to see its job.

Part 1 of 4

Tap any part of the code below, or press Next.1 of 4 explored

object:The new object. It has its own copy of every attribute.

Build your own objects

Pick an example, change it, then press Run. Say what you expect to see before you press.

Example 1 of 6A first class

__init__ runs when the object is made and stores its data on self.

Your turn: Make a second dog and print both names.

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

rex = Dog("Rex", 3)
print(rex.name, "is", rex.age)
Output
Press Run to see what it prints.

Watch a plant grow

Press Step to run one line at a time. Watch the names box: `fern.height` means the height stored on fern.

Ready. Press Step to run the first line.

  1. class Plant:
  2. def __init__(self, name):
  3. self.name = name
  4. self.height = 1
  5. def water(self):
  6. self.height += 2
  7. fern = Plant("Fern")
  8. fern.water()
  9. print(fern.name, fern.height)

Output so far

Nothing printed yet.

What Python does

Python reads the program from the top. Nothing has run yet.

Names

None yet.

Quick guesses

Guess first, then read why. A wrong guess is where the learning happens. Nothing here is scored.

Question 1 of 6

1.Two objects, one change:

class Box:
    def __init__(self):
        self.items = []
a = Box()
b = Box()
a.items.append("key")
print(len(a.items), len(b.items))

0 of 6 answered

Common class misconceptions

Each card is something learners often believe. Tap it to see what Python really does.

Misconception 1 of 4

Notes

Everything above, in words. Open it when you want the full explanation.

Read the notesOpen

You have been using objects all along

Every value in Python is an object, and every object has a type, also called its class:

Try it 1: edit me, then Run
print(type("hello"))      # <class 'str'>
print(type([1, 2]))       # <class 'list'>
print("hello".upper())    # HELLO
Output
Press Run to see what it prints.

"hello" is an object of class str. upper is a method: a function that belongs to the class and works on the object it is called on. The class str is the blueprint; each string is one object built from it. A class is the design, an object (or instance) is one thing made from that design.

Defining a class

The class statement creates a new type:

Try it 2: edit me, then Run
class Dog:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def describe(self):
        return f"{self.name} is {self.age} years old"
Output
Press Run to see what it prints.

Class names use CapitalisedWords by convention. Inside the class body are function definitions, which become the class's methods.

__init__ (with two underscores on each side) is a special method that Python calls automatically whenever a new object is created. Its job is to set the object up. The next lesson looks at it in detail.

Creating objects

Call the class like a function to create an object:

Try it 3: edit me, then Run
rex = Dog("Rex", 4)
fido = Dog("Fido", 9)
print(rex.describe())     # Rex is 4 years old
print(fido.name)          # Fido
Output
Press Run to see what it prints.

Dog("Rex", 4) creates a new, empty Dog object, then runs __init__ with self set to that object, name set to "Rex" and age set to 4. The lines self.name = name store the values on the object. These stored values are called attributes, and you read them with a dot: rex.name.

Each object has its own attributes. rex and fido were made from the same class, but changing one does not affect the other:

Try it 4: edit me, then Run
rex.age = 5
print(rex.age, fido.age)  # 5 9
Output
Press Run to see what it prints.

Methods and self

A method is a function defined inside a class. Its first parameter, called self by convention, is the object the method was called on. When you write rex.describe(), Python passes rex in as self automatically, so inside the method self.name means rex.name. Called on fido, the same method reads fido.name.

That is why every method needs self as its first parameter, and why you never pass it yourself. rex.describe() is really shorthand for Dog.describe(rex).

Methods can also change the object:

Try it 5: edit me, then Run
class Counter:
    def __init__(self):
        self.count = 0

    def click(self):
        self.count += 1

    def reset(self):
        self.count = 0

c = Counter()
c.click()
c.click()
print(c.count)            # 2
Output
Press Run to see what it prints.

The object remembers its state between calls. That is the big difference from a plain function, whose local variables vanish when it returns.

Data plus behaviour

Compare a dictionary-based design with a class:

Try it 6: edit me, then Run
# Dictionary version: the rules live elsewhere
account = {"owner": "Ana", "balance": 100}
def deposit(acc, amount):
    acc["balance"] += amount

# Class version: the rules live with the data
class Account:
    def __init__(self, owner, balance):
        self.owner = owner
        self.balance = balance

    def deposit(self, amount):
        self.balance += amount
Output
Press Run to see what it prints.

Both work. The class version keeps the operations next to the data they change, gives the thing a name (Account) and makes typos such as acc["balanse"] far less likely. With a class, everything you can do to an account is listed in one place.

Designing a class

Before writing a class, answer two questions in plain words. What does each object need to remember? Those become attributes, set in __init__. What should each object be able to do? Those become methods, named with verbs: deposit, scan, is_square. A method that answers a question usually returns a value; a method that changes the object usually returns nothing. If you find a method that does not use self at all, it may not belong in the class.

Checking types

type(obj) gives an object's class, and isinstance(obj, Class) asks whether an object belongs to a class:

Try it 7: edit me, then Run
print(type(rex).__name__)        # Dog
print(isinstance(rex, Dog))      # True
print(isinstance("rex", Dog))    # False
Output
Press Run to see what it prints.

isinstance is usually the better question, because, as the inheritance lesson shows, it also understands families of classes, just as except did with exception families.

Two names, one object

Assigning an object to another name does not copy it. Both names refer to the same object:

Try it 8: edit me, then Run
a = Counter()
b = a
b.click()
print(a.count)            # 1
Output
Press Run to see what it prints.

This is the same behaviour you saw with lists. To get a second, independent object, call the class again.

Printing objects

Printing an object of your own class shows something like <__main__.Dog object at 0x7f3a...>, with a memory address that changes every run. That is not very helpful. Until the next lesson shows how to fix it, print the attributes or a method's result instead, as in print(rex.describe()).

Syntax

The general shape of the statements in this lesson.

syntax.py
class Dog:                          # define a class
    def __init__(self, name):       # runs on creation
        self.name = name            # attribute on this object
    def speak(self):                # method: self is the object
        return self.name + " says woof"

rex = Dog("Rex")                    # create an instance
rex.name                            # read an attribute
rex.speak()                         # call a method
isinstance(rex, Dog)                # True
Output
Press Run to see what it prints.

Worked examples

Read the problem, run the code, then read why it works.

Example 1 of 2

A rectangle that knows its own maths

Beginner

Model rectangles so each one can report its area and perimeter and say whether it is a square. Create three and describe them.

Python
class Rectangle:
    def __init__(self, width, height):
        self.width = width
        self.height = height

    def area(self):
        return self.width * self.height

    def perimeter(self):
        return 2 * (self.width + self.height)

    def is_square(self):
        return self.width == self.height

shapes = [Rectangle(3, 4), Rectangle(5, 5), Rectangle(10, 2)]
for shape in shapes:
    kind = "square" if shape.is_square() else "rectangle"
    print(f"{shape.width}x{shape.height} {kind}: area {shape.area()}, perimeter {shape.perimeter()}")
Output
Press Run to see what it prints.

Predict first

How it works(open after your guess)

Each Rectangle object stores its own width and height. The methods use self to reach them, so the same area code works for every rectangle. A list of objects can be looped over like any other list.

Common pitfalls

Mistakes people make with this topic, and what to write instead.

Pitfall 1 of 3

Forgetting self in a method

Spot the bug

Can you see what is wrong? Run it to watch it go wrong, then open the fix.

Buggy code: run it
class Lamp:
    def switch_on():
        print('on')

Lamp().switch_on()
Output
Press Run to see what it prints.
Show what goes wrong and the fix

What happens

TypeError: Lamp.switch_on() takes 0 positional arguments but 1 was given

Write this instead

class Lamp:
    def switch_on(self):
        print('on')

Lamp().switch_on()

Why it happens

Python always passes the object as the first argument, so the method must have a parameter to receive it.

In the real world

Where this shows up in software people use every day.

  1. Tracking parcels

    Courier services

    A courier's app follows each parcel from collection to delivery. Every parcel object keeps its own history of scans, and knows whether it has arrived.

    Why Python fits

    Both parcels come from one class but keep separate histories, because __init__ creates a new list for each. The delivered method puts the business rule in one place, next to the data it checks.

    Python
    class Parcel:
        def __init__(self, code, destination):
            self.code = code
            self.destination = destination
            self.history = ["collected"]
    
        def scan(self, place):
            self.history.append(place)
    
        def delivered(self):
            return self.history[-1] == self.destination
    
    a = Parcel("PX1", "Leeds")
    b = Parcel("PX2", "York")
    a.scan("hub")
    a.scan("Leeds")
    b.scan("hub")
    
    for parcel in [a, b]:
        status = "delivered" if parcel.delivered() else "in transit"
        print(parcel.code, status, "->", " > ".join(parcel.history))
    Output
    Press Run to see what it prints.

Key takeaways

Tick each one you could explain to a friend.

0 of 5

Common questions

Guess the answer first, then open it.

Does self have to be called self?

Python only requires a first parameter, but every Python programmer calls it self. Using another name would confuse readers and tools.

When should I write a class instead of using a dictionary?

When the data comes with rules or actions, such as a balance that must never go negative, or when you pass the same shape of dictionary to many functions. For simple records, a dictionary is fine.

Can a method call another method?

Yes, through self: inside a method, self.area() calls the area method on the same object. This is a good way to build bigger behaviour from small methods.

Can I add a new attribute later?

Yes, obj.colour = 'red' works on most objects. It is clearer to create every attribute in __init__, so readers see the full shape of the object in one place.

Your notes

Sign in to keep private notes alongside this lesson.

Sign in to take notes

Where to go next

The quiz and the Lab live on their own pages, so this lesson stays about learning.

Finished this lesson?

Create an ID or sign in to save your progress across devices.

Create ID to save
Lessons done in this module0/3 complete
Quiz

Check what you learned

12 questions, with an explanation after every answer. A verified attempt counts towards opening the module Lab.

Lab

Keep going in the Lab

7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.

Review

Spaced review

Questions you miss in a quiz come back on a spaced schedule, so what you learned here sticks.

This lesson at a glance

The 9 lines of code this lesson uses, each with a short note. Keep it open while you do the quiz and the Lab.

What else you can search for and explore

Curious to go further? Each card opens a web search in a new tab.

References

Look things up here whenever you need the exact details.