python - 对类属性进行假继承是否不好

标签 python inheritance python-3.x pyqt pyside

首先这个问题是基于 PySide 的,但它是类属性继承的一般问题。

所以我有一个继承问题。我基本上想继承 2 个 PySide GUI 类。多重继承存在重大冲突并产生错误。基本上,我制作了一个自定义小部件,并希望将相同的小部件制作成停靠小部件( float 窗口)。

我发现易于实现的一种方法是重写 getattr 方法来重定向属性调用,如下所示。

class DockWidget(QtGui.QDockWidget):
    def __init__(self):
        super().__init__()
        self.test = Test()

        # Container is a custom widget containing the Test widget and a toolbar.
        self.setWidget(self.test.getCustomContainer())

    def __getattr__(self, name):
        """Call a property's method when the given attribute name is not found.

        Note: Gives full access to the test attribute.

        Args:
            name (str): Method or property name.
        """
        if hasattr(self.test, name):
            return self.test.__getattribute__(name)
    # end __getattr
# end class DockWidget

class Test(QtGui.QWidget):
    def doSomething(self, msg):
        print(msg)
    # end doSomething
# end Test

widg = DockWidget()
widg.doSomething("Test")

我想知道这是否真的很糟糕,以及是否有更好的方法。

最佳答案

由于DockWidgetTest都继承了QWidget,因此您可以使用mixin。这将允许您执行诸如重新实现虚拟方法之类的操作,这是使用 __getattr__ 无法实现的。

class WidgetMixin(object):
    def doSomething(self, msg):
        print(msg)

    def closeEvent(self, event):
        print(self.__class__.__name__)

class Test(WidgetMixin, QtGui.QWidget):
    def __init__(self):
        super().__init__()

class DockWidget(WidgetMixin, QtGui.QDockWidget):
    def __init__(self):
        super().__init__()

关于python - 对类属性进行假继承是否不好,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21467634/

相关文章:

Python 继承 : what is the difference?

python - 在 Tensorflow 中读取特征和标签位于同一行的 CSV 文件

python - 为什么某些代码在 Python2 中是确定性的,而在 Python 3 中是非确定性的?

python - Decimal 类可以处理的最大数字是多少?

python - 从命令行运行函数并将参数传递给函数

python - 训练模型失败,因为 'list'对象没有属性 'lower'

java - 如何在Java中为父类设置计数器而不让子类访问计数器?

python - 无法在 python 3 的子进程中使用分发 LocalCluster

c++ - C++中的递归组合

python-3.x - Python 3整数除法。如何使数学运算符与C保持一致