Codiqo

Learn Python · lesson 60 of 60 · about 11 minutes

Project: Pet Shelter

Model a shelter's animals with inheritance and save the whole shelter as JSON.

What you'll learn

  • Design a parent class and two child classes
  • Turn objects into dictionaries for JSON
  • Rebuild objects from saved JSON

Saturdays at the shelter

On Saturdays Sam helps out at the animal shelter, and the shelter keeps its list of animals as JSON, like [{"kind": "Dog", "name": "Rex", "age": 3}]. The Animal class and the reading are given: a name, an age, a sound() that's ..., describe() and to_dict(). You write Dog and Cat, which make their own sounds, rebuild each animal from its kind, print Rex (3) says Woof for each one, and save them back to shelter.json: Saved 2 animals to shelter.json. An animal of a kind the assistant doesn't know, like a rabbit, gets Unknown animal: Rabbit.

The plan

The shelter has dogs and cats. Every pet has a name and an age, and each kind makes its own sound. The shelter program will:

1. Have an Animal parent with name, age and describe()
2. Have Dog and Cat children that override sound()
3. Turn every pet into a dictionary with a to_dict() method
4. Save the list as JSON, and rebuild the pets from it

Steps 1 and 2

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

    def sound(self):
        return "..."

    def describe(self):
        return f"{self.name} ({self.age}) says {self.sound()}"

class Dog(Animal):
    def sound(self):
        return "Woof"

class Cat(Animal):
    def sound(self):
        return "Meow"

for pet in [Dog("Rex", 3), Cat("Tom", 5)]:
    print(pet.describe())

Output

Rex (3) says Woof
Tom (5) says Meow

Objects aren't JSON

json.dumps can't save a Dog object directly. Instead each pet gives back a plain dictionary, including its kind, so the program knows which class to rebuild when it loads. type(self).__name__ gives the class name as text, like "Dog".

Steps 3 and 4

import json

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

    def to_dict(self):
        return {"kind": type(self).__name__, "name": self.name, "age": self.age}

class Dog(Animal):
    pass

class Cat(Animal):
    pass

text = json.dumps([p.to_dict() for p in [Dog("Rex", 3), Cat("Tom", 5)]])
print(text)

kinds = {"Dog": Dog, "Cat": Cat}
pets = [kinds[d["kind"]](d["name"], d["age"]) for d in json.loads(text)]
print(type(pets[1]).__name__, pets[1].name)

Output

[{"kind": "Dog", "name": "Rex", "age": 3}, {"kind": "Cat", "name": "Tom", "age": 5}]
Cat Tom

From text to objects and back

kinds = {"Dog": Dog, "Cat": Cat} maps each saved kind to its class, so kinds[d["kind"]](d["name"], d["age"]) makes the right object, and checking d["kind"] in kinds first catches a kind there's no class for. describe() is inherited, but self.sound() inside it finds each child's own sound. Saving goes the other way: to_dict() uses type(self).__name__, so a Dog saves itself as "Dog" and can be rebuilt next Saturday.

Tip

A dictionary of classes, like kinds, is a neat way to choose which class to make from a piece of text.

Now try it yourself

This lesson is free in Codiqo, with 8 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.