我有一个Mixin类,生活在myModule.Mixin中。myModule.main(MyPaternalClass)中的一个新类继承自myModule.mixins.MyMixin
此mixin的目的是生成新的“child”对象,给定一个带有子类名称的字符串,但这些对象的类位于myModule.main中,而不是myModule.mixin中
我了解当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
现在,这种混合物将用于以下方面:
例如,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类不能存在于同一个模块中的原因是,它一般用于其他几个模块中
目前没有回答
相关问题 更多 >
编程相关推荐