python - 使用位于不同模块中的 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 类不能存在于同一个模块中的原因是因为它打算在其他几个模块中通用。
解决方案
推荐阅读
- php - 使用 Laravel 跳过一些行的自定义报告格式
- android - 不允许在 MAUI Blazor 中加载本地资源
- flutter - 从 pubspec.yaml 检索应用程序的当前版本
- express - Prisma 如何仅更新 update() 中的某些模型字段
- javascript - npm 包 react-virtualized 如何与可调整大小的表单输入一起使用?
- python - 在 Tkinter 或 Kivy 中显示嵌入的 html url 视频
- python - pytorch 包太大
- cassandra - Cassandra - 当另一个节点关闭时,节点卡在加入中
- ios - React Native Expo iOS 使用强密码功能不起作用
- tsql - 使用 SUM OVER 子句,如何仅在输出不大于某个值时检查总和,否则使用当前月份值?