Augusto Dias Noronha
Augusto Dias Noronha

Reputation: 864

Sharing code between two almost identical widgets PySide

I have two widgets that are almost identical, the difference is one of them has an extra button. Right now there are a bunch of methods in both which are exactly the same. What strategies do I have to share code between them? Is subclassing the best alternative here? Someday I may want to alter the superclass with functionality that wont exist in the subclass.

Upvotes: 0

Views: 66

Answers (2)

justengel
justengel

Reputation: 6320

Just use regular inheritance.

class A(QtGui.QWidget):
    def __init__(self):
        super().__init__()

        self.x = 1

        self._initProperties() # Special method for changing values with inheritance
    # end Constructor

    def _initProperties(self):
        """Initialize special inheritance properties."""
        self.setLayout(QtGui.QVBoxLayout())
    # end _initProperties

    def do_something(self):
        return self.x

class B(A):
    # def __init__(self):
    #     super().__init__()
    # 
    #     self.y = 2
    # # Because we have _initProperties that will happen at the appropriate time we don't
    # really need __init__. Just use _initProperties.
    # However, I would still use __init__. I just commented it out as an example.

    def _initProperties(self):
        """Initialize special inheritance properties.
        Note: We did not call super, so we are not using the parents _initProperties methods.
              We are overriding the parent method.
        """
        self.y = 2
        self.setLayout(QtGui.QHBoxLayout())
    # end _initProperties

    def do_something(self):
        return super().do_something() + self.y

The alternate option is to create a regular object class mixin.

class MyMixin(object):
    def __init__(self):
        super().__init__()

        self.x = 1

    def do_something(self):
        return self.x


class A(MyMixin, QtGui.QWidget):
    pass

class B(MyMixin, QtGui.QGroupBox):
    def __init__(self)
        super().__init__()

        self.y = 2

    def do_something(self):
        return super().do_something() + self.y

Python supports multiple inheritance. With this approach class A can be a QWidget while class B can be something different like a QGroupBox

Upvotes: 1

Klaus D.
Klaus D.

Reputation: 14369

You have to use subclassing. It is a very basic strategy of OOP. This intro gives a nice overview: http://www.jesshamrick.com/2011/05/18/an-introduction-to-classes-and-inheritance-in-python/ But you might find many other sources as well.

Upvotes: 0

Related Questions