🚀 Alguni Start learning

Unit 12: Your Own Types

Building things with classes.

Unit 12 of 31 in Python for kids. Its 5 lessons are Blueprints, Things That Do Things, Printing Nicely, Lots of Objects and Class Master — below is everything each one explains, and a question or two from it to try.

Every sample on this page was run through real Python before it shipped, and prints exactly what it says it prints.

This unit opens with a fortnight’s trial of everything — no card needed — or with a family plan, bought in the iPhone app. The first two units of every track are free for ever. Try it in the app.

📘 Blueprints

A shape for your own kind of thing

A class is a blueprint. It does nothing on its own — you use it to build objects, and each one holds its own information.

Python

class Dog:
    def __init__(self, name):
        self.name = name

rex = Dog("Rex")
print(rex.name)

It prints

Rex

What __init__ is for

__init__ runs the moment you build one. Its job is to put the starting information onto the new object. self is the object being built.

Python

class Dog:
    def __init__(self, name, age):
        self.name = name
        self.age = age

rex = Dog("Rex", 4)
print(rex.name, rex.age)

It prints

Rex 4

Each object keeps its own

Build two and they do not share anything. Changing one leaves the other exactly as it was.

Python

class Dog:
    def __init__(self, name):
        self.name = name

a = Dog("Rex")
b = Dog("Bo")
print(a.name)
print(b.name)

It prints

Rex
Bo

Try it yourself

What is self?

  • The name of the class
  • The particular object being worked on right now
  • A Python keyword you must never change
  • The file you are in

What does this print?

Python

class Cat:
    def __init__(self, lives):
        self.lives = lives

c = Cat(9)
c.lives = c.lives - 1
print(c.lives)

Answer them in the app

⚡ Things That Do Things

A function that lives inside a class

A function inside a class is called a method. It always takes self first, so it can reach the object it belongs to.

Python

class Dog:
    def __init__(self, name):
        self.name = name

    def speak(self):
        print(self.name + " says woof")

Dog("Rex").speak()

It prints

Rex says woof

Methods can change the object

A method can update what the object stores, so the change lasts after the method finishes.

Python

class Counter:
    def __init__(self):
        self.count = 0

    def bump(self):
        self.count = self.count + 1

c = Counter()
c.bump()
c.bump()
print(c.count)

It prints

2

Try it yourself

Why does every method start with self?

  • Python just likes it
  • So the method can see and change the object it was called on
  • To make it run faster
  • It is optional

What does this print?

Python

class Box:
    def __init__(self):
        self.items = []

    def add(self, thing):
        self.items.append(thing)

b = Box()
b.add("hat")
b.add("map")
print(len(b.items))

Answer them in the app

🖨️ Printing Nicely

Printing an object is ugly by default

Print an object and Python shows something like <__main__.Dog object at 0x7f8b1c>, which helps nobody. __str__ lets you say what it should look like instead.

Python

class Dog:
    def __init__(self, name):
        self.name = name

    def __str__(self):
        return "a dog called " + self.name

print(Dog("Rex"))

It prints

a dog called Rex

It works inside f-strings too

Anywhere Python needs your object as text, it calls __str__.

Python

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

    def __str__(self):
        return self.name.upper()

p = Pet("tig")
print(f"My pet is {p}")

It prints

My pet is TIG

Try it yourself

What must __str__ do?

  • Print the text
  • Return the text
  • Both print and return it
  • Nothing, Python fills it in

Answer it in the app

👥 Lots of Objects

A list of your own things

Objects go in lists like anything else, and then a loop can work through them.

Python

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

pets = [Pet("cat", 4), Pet("bird", 2)]
for pet in pets:
    print(pet.name, pet.legs)

It prints

cat 4
bird 2

Adding them up

Once they are in a list you can total, count or filter them just like numbers.

Python

class Pet:
    def __init__(self, legs):
        self.legs = legs

pets = [Pet(4), Pet(2), Pet(4)]
total = 0
for pet in pets:
    total = total + pet.legs
print(total)

It prints

10

Sorting your own objects

sorted needs to know *what* to sort by. key takes a small function saying which part to look at.

Python

class Kid:
    def __init__(self, name, age):
        self.name = name
        self.age = age

kids = [Kid("Ada", 11), Kid("Sam", 7)]
for kid in sorted(kids, key=lambda k: k.age):
    print(kid.name)

It prints

Sam
Ada

Try it yourself

What does this print?

Python

class Kid:
    def __init__(self, age):
        self.age = age

kids = [Kid(7), Kid(11), Kid(9)]
older = []
for kid in kids:
    if kid.age > 8:
        older.append(kid.age)
print(older)

Answer it in the app

🏆 Class Master

Try it yourself

What does this print?

Python

class Tally:
    def __init__(self):
        self.n = 0

    def up(self):
        self.n = self.n + 2

t = Tally()
t.up()
t.up()
t.up()
print(t.n)

Answer it in the app