jdwiegman
jdwiegman

Reputation: 85

Adding a method to a class within a class

Complete brain fart here and not even sure I am asking the right question. How do I add/change a method of a class that exists within a class?

I am building a QT GUI designed in QtDesigner. My Python program imports and makes a new class subclassed to the GUI file class. I want to change a method to a button within that class.

So basically I have the below, and I want to add a method to 'aButton'.

qtDesignerFile.py

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        self.aButton = QtGui.QPushButton()

myPythonFile.py

import qtDesignerFile

class slidingAppView(QMainWindow,slidingGuiUi.Ui_MainWindow):
    def __init__(self,parent=None):
        super(slidingAppView,self).__init__(parent)

Upvotes: 0

Views: 99

Answers (2)

Matthieu
Matthieu

Reputation: 4711

To add to Joran's answer, methods added like this:

def foo():
    pass

instance.foo = foo

will act like static methods (they won't have the instance passed as first argument). If you want to add a bound method, you can do the following:

from types import MethodType

def foo(instance):
    # this function will receive the instance as first argument
    # similar to a bound method
    pass

instance.foo = MethodType(foo, instance, instance.__class__)

Upvotes: 2

Joran Beasley
Joran Beasley

Reputation: 113978

self.aButton.PrintHello = lambda : print "hello!"

or

def aMethod():
    do_something()

self.aButton.DoSomething = aMethod 

either should work... probably more ways also ... this assumes aButton is a python class that inherits from Object

Upvotes: 0

Related Questions