Overriding a class method

I needed to use the functionality of a method in an outside python script that I could look at, but not alter at all. This method used a GUI to gather some information before acting on it. The code I was writing was meant to run without any user interaction, so I needed to override the GUI and gather the needed variables automatically.

Let’s say the original method was called gatherNewLensFiles. In my own script, I copied it in and made the necessary changes in my function, and then renamed it autoGatherNewLensFiles.

Original:
In theirScript.py
class LensChanger:

        def gatherNewLensFiles(self):
                their stuff
                their stuff
                their stuff
                return value

Mine:
In myScript.py

import LensChanger
def autoGatherNewLensFiles(self):
        my stuff
        my stuff
        their relevant stuff
        return value

To override the original method with my function:

#create an instance of the class
changer = LensChanger()

#replace gatherNewLensFiles with autoGatherNewLensFiles for this object only!
changer.gatherNewLensFile = autoGatherNewLensFile.__get__(changer, LensChanger)

#call the overriding method
changer.gatherNewLensFile()

This is the explicit way, which I use here for my own understanding. You could also use the more familiar . operator to bind the class method. For a much more thorough discussion, check out Stack Overflow here:
https://stackoverflow.com/questions/394770/override-a-method-at-instance-level

Leave a Reply

Your email address will not be published. Required fields are marked *