A cookie cutter
The cutter is not a cookie. You use it to make cookies.
14OBJECTS · THE MOLD
A class is a mold. It says what every robot made with it will know. Then you use it to make real robots.
IN REAL LIFE
A mold is the plan. You use it to make the real things.
The cutter is not a cookie. You use it to make cookies.
The tray has the shape. Water goes in, ice cubes come out.
Every form asks for a name. Each person writes their own.
LOOK FIRST
class Robot: starts the mold. Mold names start with a capital letter.
The mold's setup job. It runs by itself each time a new robot is made. Two _ before and two after.
self means “this robot itself”. self.name = name writes the name inside this robot.
STEP BY STEP
Take it slow. The first 4 lines are only the plan. Line 5 makes a real robot.
class Robot:Starts the mold called Robot. No robot exists yet. def __init__(self, name):The setup job. It gets the new robot (self) and a name. self.name = nameWrites the name inside this robot. self.battery = 100Every new robot starts full: 100.bolt = Robot("Bolt")Use the mold! Now a real robot exists. You do not write self: Python fills it in.print(bolt.name)Read its data with a dot: Boltprint(bolt.battery)Shows 100Remember the turtle? turtle.Turtle is a mold too. t = turtle.Turtle() used it to make one turtle.
RUN IT
Guess first. Then run real Python and check.
class Robot:
def __init__(self, name, color):
self.name = name
self.color = color
rita = Robot("Rita", "green")
print(rita.name)
print(rita.color)What will Python show?
PyBot's hint
Ready. Press Run Python.
Pyodide 314.0.3 runs CPython in your browser with WebAssembly.
Open-source under the Mozilla Public License 2.0. License
Now change one thing: Change "green" to your favorite color. Then add: print(rita.name, "is", rita.color)
YOUR TURN
Try each tiny question. A wrong answer becomes something to review.
Which one is like a class?
Which line starts a mold the right way?
class Cat:
def __init__(self, name):
self.name = nameHow many cats exist after this code?
class Cat:
def __init__(self, name):
self.name = name
tom = Cat("Tom")
print(tom.name)What does Python show?
Inside the mold, what does self mean?
class Robot:
def __init__(self, name):
self.name = name
self.battery = 100
zap = Robot("Zap")
print(zap.battery)What does Python show?
PyBot made a robot but forgot its name. The mold needs a name inside the ( ). Make it show: Pip
PipOUTPUT
Want a fresh start? Clear only this page.
class names the mold, __init__ sets up each new robot, and self means “this robot”. Next: many robots from one mold!