
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:
__init__(self, name, hp, armor)callssuper().__init__(name, hp)and then storesarmor.- Override
take_hit(damage): armor absorbs that much damage (but the damage can't go below0), then pass the reduced damage to the parent'stake_hit. - Override
describe(): return the parent's description followed by[armor N], e.g.Pebble (30 hp) [armor 4].
Write Golem, a child of Creature:
__init__(self, name, hp, armor)callssuper().__init__(name, hp)and then storesarmor.- Override
take_hit(damage): armor absorbs that much damage (but the damage can't go below0), then pass the reduced damage to the parent'stake_hit. - Override
describe(): return the parent's description followed by[armor N], e.g.Pebble (30 hp) [armor 4].
main.py Python sleeping
Press Run to try your code, then Check to test it.