【发布时间】:2017-02-14 04:32:37
【问题描述】:
我无法让多重动态继承工作。这些示例对我来说最有意义(here 和 here),但是一个示例中没有足够的代码让我真正理解发生了什么,而另一个示例在我更改时似乎不起作用满足我的需要(代码如下)。
我正在创建一个适用于多个软件包的通用工具。在一个软件中,我需要从 2 个类继承:1 个特定于软件的 API mixin 和 1 个 PySide 类。在另一个软件中我只需要从 1 PySide 类继承。
我能想到的最不优雅的解决方案是只创建 2 个单独的类(使用所有相同的方法)并根据正在运行的软件调用其中一个。我觉得有更好的解决方案。
这是我正在使用的:
## MainWindow.py
import os
from maya.app.general.mayaMixin import MayaQWidgetDockableMixin
# Build class
def build_main_window(*arg):
class Build(arg):
def __init__(self):
super( Build, self ).__init__()
# ----- a bunch of methods
# Get software
software = os.getenv('SOFTWARE')
# Run tool
if software == 'maya':
build_main_window(maya_mixin_class, QtGui.QWidget)
if software == 'houdini':
build_main_window(QtGui.QWidget)
我目前收到此错误:
# class Build(arg):
# TypeError: Error when calling the metaclass bases
# tuple() takes at most 1 argument (3 given) #
感谢您的帮助!
编辑:
## MainWindow.py
import os
# Build class
class BuildMixin():
def __init__(self):
super( BuildMixin, self ).__init__()
# ----- a bunch of methods
def build_main_window(*args):
return type('Build', (BuildMixin, QtGui.QWidget) + args, {})
# Get software
software = os.getenv('SOFTWARE')
# Run tool
if software == 'maya':
from maya.app.general.mayaMixin import MayaQWidgetDockableMixin
Build = build_main_window(MayaQWidgetDockableMixin)
if software == 'houdini':
Build = build_main_window()
【问题讨论】:
-
那是因为它试图继承
args本身的元组。如果您想要动态多重继承,请使用type(name, bases, dct)。 -
为避免错误,您可以在使用时在 *arg 之前添加星号:class Build(*arg)。请注意,构造函数内部对 super 的调用可能会调用不同的东西,具体取决于您作为 arg 传递的内容。
标签: python class inheritance dynamic