我有一个基类和几个子类。每个子类都有一个名为“regex”的属性,其中包含一个字符串:
# 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()
我想使用每个类的正则表达式作为键在 action_types 字典中注册所有子类。我希望注册类的逻辑仅限于基类。
上面的例子是行不通的,我相信这是因为 Dance 和 Sing 变量在使用时在命名空间中还不可用。
有没有办法在类初始化的时候把子类注册到字典中?
最佳答案
这不是你想要的方式。
class ActionRegistry(type):
registry = {}
def __init__(cls, name, bases, dic):
if 'regex' in dic:
cls.registry[dic['regex']] = cls
super(ActionRegistry, cls).__init__(name, bases, dic)
class Action(object):
__metaclass__ = ActionRegistry
class Sing(Action):
regex = r'^SING [0-9]+'
class Dance(Action):
regex = r'^DANCE [0-9]+'
关于python - 在 python 中将所有子类组织到字典中的好方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7654272/