I have a base class and several subclasses. Each sub class has an attribute called “regex” containing a string:
# module level dictionary
action_types = {}
class Action():
regex = '.*'
@classmethod
def register_action(cls):
action_types[cls.regex] = cls
class Sing(Action):
regex = r'^SING [0-9]+'
Sing.register_action()
class Dance(Action):
regex = r'^DANCE [0-9]+'
Dance.register_action()
I want to register all the sub classes in the action_types dictionary using each classes’ regex as a key. I want the logic to register the class to be confined to the base class.
The above example doesn’t work, and I believe this is because the Dance and Sing variables are not yet available in the namespace when they are used.
Is there any way to register the sub classes in the dictionary during the class initialization?
That’s not how you want to do it.