
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
- Finish
Spell.__init_subclass__:- if
elementisNone, raiseTypeError(every spell needs one); - store it as
cls.element; - add the class to
Spell.registryunder its element.
- if
- Finish the classmethod
Spell.create(element): return a new instance of the registered class, or raiseValueError(f"unknown element: {element}").
- Finish
Spell.__init_subclass__:- if
elementisNone, raiseTypeError(every spell needs one); - store it as
cls.element; - add the class to
Spell.registryunder its element.
- if
- Finish the classmethod
Spell.create(element): return a new instance of the registered class, or raiseValueError(f"unknown element: {element}").
main.py Python sleeping
Press Run to try your code, then Check to test it.