如何从类体中获取当前类的引用?

时间:2010-02-03 11:28:41

标签: python inheritance class

我想在基类中保留(所有非立即包含的)子类的字典,以便我可以从字符串中实例化它们。我这样做是因为CLSID是通过Web表单发送的,所以我想将选择限制为从子类设置的选项。 (我不想eval() / globals()类名。

class BaseClass(object):
    CLSID = 'base'
    CLASSES = {}

    def from_string(str):
        return CLASSES[str]()

class Foo(BaseClass):
    CLSID = 'foo'
    BaseClass.CLASSES[CLSID] = Foo

class Bar(BaseClass):
    CLSID = 'bar'
    BaseClass.CLASSES[CLSID] = Bar

这显然不起作用。但是对于init有没有像@classmethod这样的东西?这个想法是这个类方法只会在读取每个类时运行一次,并使用基类注册该类。然后可以使用以下内容:(还可以在FooBar中保存额外的行)

class BaseClass(object):
    CLSID = 'base'
    CLASSES = {}

    @classmethod
    def __init__(cls):
        BaseClass.CLASSES[cls.CLSID] = cls 

    def from_string(str):
        return CLASSES[str]()

我考虑在__subclasses__上使用filter()然后使用CLSID,但这仅适用于直接子类。

所以,希望我解释了我的目的,问题是如何使这项工作?或者我是以完全错误的方式解决这个问题?

2 个答案:

答案 0 :(得分:6)

不可避免地将其与基类联系起来:

class AutoRegister(type):
  def __new__(mcs, name, bases, D):
    self = type.__new__(mcs, name, bases, D)
    if "ID" in D:  # only register if has ID attribute directly
      if self.ID in self._by_id:
        raise ValueError("duplicate ID: %r" % self.ID)
      self._by_id[self.ID] = self
    return self

class Base(object):
  __metaclass__ = AutoRegister
  _by_id = {}
  ID = "base"

  @classmethod
  def from_id(cls, id):
    return cls._by_id[id]()

class A(Base):
  ID = "A"

class B(Base):
  ID = "B"

print Base.from_id("A")
print Base.from_id("B")

或者将不同的问题实际分开:

class IDFactory(object):
  def __init__(self):
    self._by_id = {}
  def register(self, cls):
    self._by_id[cls.ID] = cls
    return cls

  def __call__(self, id, *args, **kwds):
    return self._by_id[id](*args, **kwds)
  # could use a from_id function instead, as above

factory = IDFactory()

@factory.register
class Base(object):
  ID = "base"

@factory.register
class A(Base):
  ID = "A"

@factory.register
class B(Base):
  ID = "B"

print factory("A")
print factory("B")

你可能已经选择了我喜欢哪一个。与类层次结构分开定义,您可以轻松扩展和修改,例如通过注册两个名称(使用ID属性只允许一个):

class IDFactory(object):
  def __init__(self):
    self._by_id = {}

  def register(self, cls):
    self._by_id[cls.ID] = cls
    return cls

  def register_as(self, name):
    def wrapper(cls):
      self._by_id[name] = cls
      return cls
    return wrapper

  # ...

@factory.register_as("A")  # doesn't require ID anymore
@factory.register          # can still use ID, even mix and match
@factory.register_as("B")  # imagine we got rid of B,
class A(object):           #  and A fulfills that roll now
  ID = "A"

您还可以将工厂实例保持在基础“内部”,同时保持解耦:

class IDFactory(object):
  #...

class Base(object):
  factory = IDFactory()

  @classmethod
  def register(cls, subclass):
    if subclass.ID in cls.factory:
      raise ValueError("duplicate ID: %r" % subclass.ID)
    cls.factory[subclass.ID] = subclass
    return subclass

@Base.factory.register  # still completely decoupled
                        # (it's an attribute of Base, but that can be easily
                        # changed without modifying the class A below)
@Base.register  # alternatively more coupled, but possibly desired
class A(Base):
  ID = "A"

答案 1 :(得分:3)

你可以用metaclasses来为你做这项工作,但我认为一个更简单的解决方案就足够了:

class BaseClass(object):
    CLASS_ID = None
    _CLASSES = {}

    @classmethod
    def create_from_id(cls, class_id):
        return CLASSES[class_id]()

    @classmethod
    def register(cls):
        assert cls.CLASS_ID is not None, "subclass %s must define a CLASS_ID" % cls
        cls._CLASSES[cls.CLASS_ID] = cls

然后定义子类只需使用:

class Foo(BaseClass):
    CLASS_ID = 'foo'

Foo.register()

最后使用BaseClass中的factory方法为您创建实例:

foo = BaseClass.create_from_id('foo')

在此解决方案中,在类定义之后,必须调用register类方法将子类注册到基类中。此外,如果用户忘记定义基类,则默认CLASS_ID为None,以避免覆盖注册表中的基类。