Teddy bears
Same factory mold. You name yours, your friend names theirs.
14OBJECTS ยท MANY ROBOTS
Every robot made with the mold keeps its own data. And the mold can give them all the same actions.
IN REAL LIFE
Things from one mold look alike, but each one is its own.
Same factory mold. You name yours, your friend names theirs.
The same shirt for everyone, but each one has a different name and number.
Same cutter. One gets pink icing, one gets chocolate.
LOOK FIRST
def greet(self): inside the class gives every robot a greet action.
When bolt.greet() runs, self is bolt. When rita.greet() runs, self is rita.
bolt.work() lowers only Bolt's battery. Rita keeps hers.
STEP BY STEP
The mold now has an action. Watch who self is each time.
class Robot:The mold. def __init__(self, name):Setup: each new robot gets a name. self.name = nameWrites it inside this robot. def greet(self):An action for every robot. Its first word is always self. print("Hi, I am", self.name)Uses this robot's own name.bolt = Robot("Bolt")Robot number 1.rita = Robot("Rita")Robot number 2, from the same mold.bolt.greet()self is bolt. Shows: Hi, I am Boltrita.greet()self is rita. Shows: Hi, I am RitaRUN IT
Guess first. Then run real Python and check.
class Robot:
def __init__(self, name):
self.name = name
self.battery = 100
def work(self):
self.battery = self.battery - 30
bolt = Robot("Bolt")
rita = Robot("Rita")
bolt.work()
print(bolt.name, bolt.battery)
print(rita.name, rita.battery)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: Add rita.work() two times before the prints. What is Rita's battery now?
YOUR TURN
Try each tiny question. A wrong answer becomes something to review.
How many cookies have sprinkles?
class Dog:
def __init__(self, name):
self.name = name
a = Dog("Rocky")
b = Dog("Luna")
c = Dog("Max")How many dogs did the mold make?
class Robot:
def __init__(self, name):
self.name = name
def greet(self):
print("Hi, I am", self.name)
rita = Robot("Rita")
rita.greet()What does Python show?
class Cat:
def __init__(self, name):
self.name = name
self.hungry = True
tom = Cat("Tom")
luna = Cat("Luna")
tom.hungry = False
print(luna.hungry)What does Python show?
When bolt.greet() runs, who is self?
Which line makes Bolt use its greet action?
Both robots should work once, but PyBot made Bolt work two times. Fix one line. Make it show: Bolt 70 and Rita 70
Bolt 70 Rita 70OUTPUT
PyBot forgot one word in the greet action. Every action in a mold needs self first. Make it show: Hi, I am Pip
Hi, I am PipOUTPUT
Want a fresh start? Clear only this page.
The class gives every robot the same data names and the same actions. self makes each action use its own robot. You reached the end of the path for now. Great work!