Code

Is-a: Inheritance & super()

Sometimes one class is a special kind of another: a golem is a creature. Inheritance lets a child class reuse everything from its parent and change only what's different.

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

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

class Owl(Creature):          # Owl inherits from Creature
    def speak(self):          # override: replace the parent's version
        return "Hoo!"

print(Owl("Nib").name)        # Nib  (inherited __init__)
print(Owl("Nib").speak())     # Hoo!

To extend a parent method instead of replacing it, call the parent's version with super():

class Bat(Creature):
    def __init__(self, name, wingspan):
        super().__init__(name)   # let Creature do its part
        self.wingspan = wingspan

isinstance(Owl("Nib"), Creature) is True: an owl counts as a creature.

Pip tip: prefer composition (has-a) by default. Use inheritance when the child truly is a kind of the parent.

Assignment

Write Golem, a child of Creature:

  1. __init__(self, name, hp, armor) calls super().__init__(name, hp) and then stores armor.
  2. Override take_hit(damage): armor absorbs that much damage (but the damage can't go below 0), then pass the reduced damage to the parent's take_hit.
  3. Override describe(): return the parent's description followed by [armor N], e.g. Pebble (30 hp) [armor 4].