python · level 2 · unit 7 · lesson 1
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
A is a blueprint, and each is built from it.
A class describes a kind of thing, like a pet. Each object made from it is one real pet with its own details. You have used objects all along: every string is an object of the str class.
Inside the class, __init__ is a method that runs whenever a new object is made. Its first parameter, , is that new object, so self.name = name stores the name as an on it.
Call the class like a function to make an object: Pet("Rex", 4). Read its attributes with a dot, like rex.name.
class Pet:
def __init__(self, name, age):
self.name = name
self.age = age
rex = Pet("Rex", 4)
mog = Pet("Mog", 11)
print(rex.name, rex.age)
print(mog.name) Class names start with a capital letter, like Pet, so they stand out from variables.
guess first
Two players, one blueprint. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
class Player:
def __init__(self, name):
self.name = name
self.score = 0
ana = Player("Ana")
ben = Player("Ben")
ana.score = 10
print(ana.score, ben.score)
your turn
Your turn. Design a book.
Fill in the word that stores the author on the new object. Then make a book of your own, with a title and an author.
fix it
The car forgot its colour. Can you fix it?
- Read the error: the Car object has no attribute called colour. Which line was meant to store it?
- Line 4 stores the colour in a plain variable, which vanishes when
__init__ends. It must go on the object. - Change line 4 to self.colour = colour, then run.
nailed it
you built your own kind of value. :D
- A class is a blueprint, and each object is built from it.
__init__runs when an object is made, andselfis it.- Store attributes with
self.name = name, read them with a dot.
new words in your collection
- class
- object
- attribute
- self
This lesson isn’t saved. A free account remembers every lesson you finish.