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 = namestores data on the object. Read it back withrex.name.Methods
A
definside 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
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.
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
rex = Dog("Rex", 3)
print(rex.name, "is", rex.age)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.
- class Plant:
- def __init__(self, name):
- self.name = name
- self.height = 1
- def water(self):
- self.height += 2
- fern = Plant("Fern")
- fern.water()
- 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 notesNotesOpenClose
Syntax
The general shape of the statements in this lesson.
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) # TruePress 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
Model rectangles so each one can report its area and perimeter and say whether it is a square. Create three and describe them.
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()}")Press Run to see what it prints.Predict first
How it works(open after your guess)
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.
class Lamp:
def switch_on():
print('on')
Lamp().switch_on()Press Run to see what it prints.Show what goes wrong and the fixWhat goes wrong and the fix
In the real world
Where this shows up in software people use every day.
- Courier services
Tracking parcels
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. Thedeliveredmethod puts the business rule in one place, next to the data it checks.Pythonclass 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))OutputPress 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?
When should I write a class instead of using a dictionary?
Can a method call another method?
Can I add a new attribute later?
Your notes
Sign in to keep private notes alongside this lesson.
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.
Check what you learned
12 questions, with an explanation after every answer. A verified attempt counts towards opening the module Lab.
Keep going in the Lab
7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.
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.
- type()Find out what type of value an object is.
- property()Create a managed attribute for a class.
- getattr()Read an attribute when its name is stored in a string.
- setattr()Set an attribute on an object using its name as text.
- ClassesOfficial Python documentation
- A first look at classesOfficial Python documentation