Objects and inheritance 0/1

Lesson 19 of 21

Objects and inheritance

Define classes, share behaviour through inheritance, and teach objects how to print and add.

Part 1 of 8 Data and its functions

Data and the functions that change it

Say we are writing a small battle game. Each unit in it has a name, some hit points, and a maximum it can't be healed past. Two things happen to a unit: it gets hit, and it gets healed. Whatever happens, its hit points have to stay between 0 and that maximum.

You can already write this with what you know. A unit is a record, a data class with three fields, and each thing that happens to a unit is a function that takes the record:

Sign up to run
@dataclass
class Unit:
    name: str
    hp: int
    max_hp: int

def take_hit(unit, damage):
    unit.hp = max(unit.hp - damage, 0)

def heal(unit, amount):
    unit.hp = min(unit.hp + amount, unit.max_hp)

aria = Unit('Aria', 10, 10)
take_hit(aria, 4)
heal(aria, 9)
print(aria.hp)
aria.hp -= 15
print(aria.hp)

The program prints 10 and then −5. Aria takes 4 damage and drops to 6, the heal of 9 stops at her maximum of 10, and so far the rule holds. Then the line aria.hp -= 15 changes the record directly. It skips both functions and leaves her at −5 hit points.

The rule about 0 and the maximum is written inside take_hit and heal, but nothing ties those two functions to the record, which is why that last line could go around them. In a real game they would sit among dozens of other functions, and everyone working on the code would have to know they exist and remember to use them instead of changing hp by hand. Every call also has to pass the unit in.

Strings and lists don't work this way. When you write nums.append(4), the operation comes with the list: you don't go looking for a separate function that adds to lists. A class lets you make your own kind of value that works like that. It says, in one place, what data each value holds and which methods act on it.

You have seen two small pieces of this already. The ticketer kept a number that only take could change, and the @dataclass line turned a class statement into a record by writing its constructor for you. Now we write a class ourselves, with its methods.