Meloun
Meloun

Reputation: 15049

How to extend a class instance?

I have an instance..

groupCell = QtGui.QGroupBox()
print groupCell.title() #this class has a method title()

I am not able to change anything of this instance, it comes how it is...

I need to extend this instance (add some methods etc.)

class GroupBoxWithCheckbox (QtGui.QGroupBox):
    def __init__(self, basegroupbox, checkbox):
        #something like self = basegroupbox ?
        self.checkbox = checkbox
    def method(self):
        pass

and finally

groupCellWithCheckBox = GroupBoxWithCheckbox(groupCell, checkbox)
print groupCellWithCheckBox.title()

I have to get the same title as with groupCell.

Upvotes: 0

Views: 98

Answers (2)

Matthew
Matthew

Reputation: 2300

You can define a new class extending QtGui.QGroupBox that looks like this:

class GroupBoxWithCheckbox(QtGui.QGroupBox):

    def __init__(self, checkbox):
        super(GroupBoxWithCheckbox, self).__init__()
        self.checkbox = checkbox

    def method(self):
        pass

Then you can simply make groupCell an instance of this class, and pass in a checkbox when you initialise it:

groupCell = GroupBoxWithCheckbox(checkbox)

That will have the same effect as what you are trying to do here.


Edit, since new information has been provided:

Since we're talking Python here, you can dynamically add things to any instance you want. It's totally possible to do this:

groupCell.checkbox = checkbox

Even if the groupCell doesn't have a checkbox property. The property will be added when you set it, as in my snippet above. You could use that to do what you want. It's kind of a weird thing to do, and I don't recommend it, but it would work. The alternative is to make a wrapper class of some sort:

class GroupBoxWithCheckbox(object):
    def __init__(self, groupbox, checkbox):
        self.groupbox = groupbox
        self.checkbox = checkbox

groupCell = GroupBoxWithCheckbox(groupCell, checkbox)

And then any time you want to access a method of the original GroupBox, you can do something like

groupCell.groupbox.title()

groupCell.groupbox will contain all of the methods that the original GroupBox did, but you'll also have access to groupCell.checkbox.

The latter solution is what I would implement if I were coding this.

Upvotes: 1

falsetru
falsetru

Reputation: 369004

Call base class constructor using super:

class GroupBoxWithCheckbox(QtGui.QGroupBox):
    def __init__(self, basegroupbox, checkbox):
        super(GroupBoxWithCheckbox, self).__init__()
        self.checkbox = checkbox
        self.basegroupbox = basegroupbox
    def title(self):
        return self.basegroupbox.title()

Upvotes: 0

Related Questions