Lesson 19 of 30

Lesson 19 ? Simple classes

Title: Make a blueprint for pets and robots

Description: Learn the first idea of classes with tiny objects that have names and actions.

Why it matters for kids: Classes help you create many similar things without copying all the code.


1. First class

pythonpython
class Pet:
    def __init__(self, name):
        self.name = name

pet = Pet("Mochi")
print(pet.name)

Pet is the blueprint. pet is one real pet made from it.


2. Add an action

pythonpython
class Pet:
    def __init__(self, name):
        self.name = name

    def say_hello(self):
        print(f"{self.name} says hello!")

pet = Pet("Luna")
pet.say_hello()

3. Robot class

pythonpython
class Robot:
    def __init__(self, name, color):
        self.name = name
        self.color = color

    def introduce(self):
        print(f"I am {self.name}, the {self.color} robot.")

robot = Robot("Beep", "yellow")
robot.introduce()

4. Many objects

pythonpython
class Snack:
    def __init__(self, name):
        self.name = name

    def eat(self):
        print(f"Yum! Eating {self.name}.")

apple = Snack("apple")
cookie = Snack("cookie")

apple.eat()
cookie.eat()

5. Easy examples

pythonpython
class Player:
    def __init__(self, name, score):
        self.name = name
        self.score = score

player = Player("Ava", 100)
print(player.name)
print(player.score)
pythonpython
class Door:
    def __init__(self, color):
        self.color = color

    def open(self):
        print(f"The {self.color} door opens.")

Door("red").open()

6. Mini challenge

Click each example to open it.

Example 1

Create a simple Pet class.

Example 2

Give the pet a name.

Example 3

Print the pet name.

Example 4

Add say_hello method.

Example 5

Create two pet objects.

Example 6

Create a robot class.

Example 7

Give the robot a color.

Example 8

Add a robot introduce method.

Example 9

Create a door class.

Example 10

Create a dragon class.