Learn Python · lesson 42 of 60 · about 9 minutes
Classes and Objects
Keep track of Sam's homework: create your own types with class, and build objects that hold their own data.
What you'll learn
- Define a class
- Write an __init__ method
- Create objects and read their attributes
A homework planner
Each piece of homework has two things that belong together: a subject and how many days until it's due. A Homework class describes that once, and each piece Sam types in, like maths 2, becomes a Homework object with its own subject and days. The assistant keeps them in a list, skips lines that aren't homework, and says which piece comes first: 2 to do, maths first (due in 2 days), with tomorrow and today for 1 and 0.
A blueprint for things
A class is a blueprint. An object is one thing built from it. A Pet class could describe what every pet has; each actual pet is an object.
__init__ runs when an object is created and sets up its attributes. self means "this particular object".
Two pets from one class
class Pet:
def __init__(self, name, kind):
self.name = name
self.kind = kind
a = Pet("Phoebe", "penguin")
b = Pet("Rex", "dog")
print(a.name, "is a", a.kind)
print(b.name, "is a", b.kind)Output
Phoebe is a penguin
Rex is a dogObjects are independent
Changing one object's attribute doesn't affect any other object made from the same class.
Separate data
class Counter:
def __init__(self):
self.count = 0
x = Counter()
y = Counter()
x.count += 5
print(x.count, y.count)Output
5 0A list of objects
Objects go in lists like anything else. A loop then gives you one object at a time, and you reach its data with a dot. To find the one with the fewest days, keep the best so far and replace it only when a piece is strictly sooner, so on a tie the first one stays.
Finding the soonest
class Homework:
def __init__(self, subject, days):
self.subject = subject
self.days = days
pile = [Homework("art", 4), Homework("maths", 2), Homework("french", 2)]
soonest = pile[0]
for piece in pile:
if piece.days < soonest.days:
soonest = piece
print(soonest.subject, soonest.days)Output
maths 2Tip
Class names use CapitalisedWords (Pet, BankAccount). Variables and functions use lower_case. The style makes classes easy to spot.
Now try it yourself
This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.