在python中将所有子类组织成字典的好方法?

时间:2011-10-04 21:29:31

标签: python regex

我有一个基类和几个子类。每个子类都有一个名为“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变量尚不可用。

有没有办法在类初始化期间在字典中注册子类?

3 个答案:

答案 0 :(得分:7)

这不是你想要的方式。

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]+'

答案 1 :(得分:0)

这有效:

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()

答案 2 :(得分:0)

在课堂初始化期间不要尝试这样做。

这是一种更简单的方法:

action_types = {}

class Action():
    regex = '.*'

class Sing(Action):
    regex = r'^SING [0-9]+'

class Dance(Action):
    regex = r'^DANCE [0-9]+'

def register_action(cls):
    action_types[cls.regex] = cls

for cls in (Sing, Dance):
    register_action(cls)