|
| 1 | +from dataclasses import dataclass |
| 2 | +from typing import List |
| 3 | + |
| 4 | +@dataclass(frozen=True) |
| 5 | +class Animal: |
| 6 | + name: str |
| 7 | + size: str |
| 8 | + |
| 9 | +@dataclass(frozen=True) |
| 10 | +class Person: |
| 11 | + name: str |
| 12 | + age: int |
| 13 | + |
| 14 | +@dataclass(frozen=True) |
| 15 | +class Tree[T]: |
| 16 | + parent: T |
| 17 | + children: List[T] |
| 18 | + |
| 19 | + def print_tree(self): |
| 20 | + print(self.parent) |
| 21 | + for child in self.children: |
| 22 | + print(child) |
| 23 | + |
| 24 | +fatma = Person(name="Fatma", age=4) |
| 25 | +aisha = Person(name="Aisha", age=6) |
| 26 | +imran = Person(name="Imran", age=30) |
| 27 | +family_tree = Tree[Person](parent=imran, children=[fatma, aisha]) |
| 28 | + |
| 29 | +cats = Animal(name="Cat", size="Small") |
| 30 | +dogs = Animal(name="Dog", size="Medium") |
| 31 | +mammals = Animal(name="Mammals", size="Variable") |
| 32 | +species_tree = Tree[Animal](parent=mammals, children=[cats, dogs]) |
| 33 | + |
| 34 | +family_tree.print_tree() |
| 35 | +species_tree.print_tree() |
| 36 | + |
| 37 | +# Task 11: |
| 38 | +# Experiment with mypy and make sure that the family tree only takes `Person` types and the species tree only takes `Animal` types. |
| 39 | +# |
| 40 | +# We are going to add printing to the above code. |
| 41 | +# |
| 42 | +# Unlike our earlier example, we want to avoid having to create two |
| 43 | +# separate looping methods to print out an entire tree for each datatype. |
| 44 | +# So we have created a single looping function within Tree that will work for any datatype. |
| 45 | +# |
| 46 | +# Currently the `Tree.print_tree()` function doesn't do anything. |
| 47 | +# |
| 48 | +# Add some appropriate methods to each of the Animal and Person classes to allow it to work. |
| 49 | +# |
| 50 | +# **Stretch task** |
| 51 | +# |
| 52 | +# Think of another type of data that can be organised into a tree. |
| 53 | +# |
| 54 | +# Add a new class for this, instantiate some variables, and have the existing `Tree` class print it out. |
| 55 | +# Here is an example of what should be printed out |
| 56 | +''' |
| 57 | +Imran (30 years old) |
| 58 | +- Fatma (4 years old) |
| 59 | +- Aisha (6 years old)) |
| 60 | +Mammals (Variable size) |
| 61 | +- Cat (Small size) |
| 62 | +- Dog (Medium size) |
| 63 | +''' |
0 commit comments