← All lessons

Polymorphism

Sign in · Sign up

Lesson 10.8

Different classes can have a method with the same name that works in their own way:

class Hero:
    def attack(self):
        return 5

class Warrior(Hero):
    def attack(self):
        return 10

class Mage(Hero):
    def attack(self):
        return 8
  • "polymorphism" means "many forms": one call hero.attack() gives different damage;
  • what matters is the shared contract: all heroes have attack(), and the children override it;
  • that's why a list of different heroes can be handled the same way — with one loop.

The check gives a list of heroes: name, hp, strength and mana. A warrior's attack() gives 10 + strength, a mage's gives 8 + mana // 10. Print <name>: damage <attack>.

Hint

Both children override the same attack method.

A warrior's damage depends on strength, a mage's on mana, so the results are different. Your own fields must be created in the constructor with super() first.