首页 > 解决方案 > 使用位于不同模块中的 Mixin 类中的 getattr 从调用者那里获取类

问题描述

我在 myModule.mixins 中有一个 Mixin 类。myModule.main (MyPaternalClass) 中的一个新类继承自 myModule.mixins.MyMixin。

这个 mixin 的目的是在给定带有子类名称的字符串的情况下生成新的“子”对象,但是这些对象的类位于 myModule.main 中,而不是 myModule.mixins 中

我了解当 Mixin 位于同一模块中时如何使用:

this = sys.modules[__name__]
cls = getattr(this, objType)
new_cls_inst = cls()

但是,当 mixin 类存在于自己的模块中时,我很难找到一种好的方法来做到这一点。

前任。myModule.mixins

class MyMixin(object):
  def new_obj(self, objType):
    cls = #Get the class
    newobj = cls()
    return newobj

现在,该 mixin 将用于以下用途:

前任。myModule.main

from .mixin import MyMixin
class MyPaternalClass(MyMixin):
  def __init__(self):
     super(MyPaternalClass, self).__init__()
     self.children = []

  def add_child(self, child_type):
    self.children.append(self.new_obj(child_type))

class Son(object):
  def __init__(self):
    pass

class Daughter(object):
  def __init__(self):
    pass

用法如下所示:

new_parent = MyPaternalClass()
new_parent.add_child('Son')
new_parent.add_child('Daughter')

mixin 类不能存在于同一个模块中的原因是因为它打算在其他几个模块中通用。

标签: pythonpython-2.7

解决方案


推荐阅读