Code

Self-Registering Spells

When a class is subclassed, Python calls the parent's __init_subclass__ with the new subclass. It's an implicit classmethod, and any keyword arguments in the class line are passed to it:

class Spell:
    def __init_subclass__(cls, element=None, **kwargs):
        super().__init_subclass__(**kwargs)
        print("new spell:", cls.__name__, element)

class Fireball(Spell, element="fire"):
    pass
# prints: new spell: Fireball fire

This is perfect for plugin registries: subclasses register themselves just by existing, so nobody has to remember to add them to a list. Always forward **kwargs to super().__init_subclass__ so classes can cooperate in multiple inheritance.

Assignment

  1. Finish Spell.__init_subclass__:
    • if element is None, raise TypeError (every spell needs one);
    • store it as cls.element;
    • add the class to Spell.registry under its element.
  2. Finish the classmethod Spell.create(element): return a new instance of the registered class, or raise ValueError(f"unknown element: {element}").