I'm trying to replace a function defined within a class in order to modify its function (as in inner workings) without changing the actual code. I've never done this before, hence, having some problems while replacing it. Changing the code will have me accessing the package within my python library which is not much of an option.
For example if the module was called testMOD
class testMOD(object):
def testFunc(self, variable):
var = variable
self.something = var + 12
Then I would import testMOD, define a class (mytest = testMOD()), and access the defined function within the class, testFunc, and change it to already defined function.
For instance,
from somemodule import testMOD
mytest = testMOD()
def alternativeFunc(self, variable):
var = variable
self.something = var + 1.2
#problem here
mytest.testFunc = alternativeFunc
As you can see, if I just manually overwrite(?) the function in the class with my defined function it won't work properly. It doesn't give any syntax errors, however, the problem is that the replaced function thinks that the 'self' is another variable for the function and says that it requires another argument for the 'variable' variable (I guess that wasn't a good name).
What I want to do is to make the replacing function to be exactly the same thing as the replaced function, but with additional code or some minor modifications. However, the 'self' is pretty much not working as it should be in a class. Would there be a way to properly implement a defined function to replace a function of an imported class?
I suggest 4 solutions, from the worst to the best (IMHO), but of course it also depends on your specific constraints:
Replace the instance method (1): I use the fact that functions are descriptors in Python, so that I can use the
__get__
method onAlternativeFunc
to get it as a method of the instancemytest
and overwrite thetestFunc
method of the instancemytest
(without overwriting the class method):Replace the instance method (2): This time, I use
types.MethodType
which is a bit more readable than the first solution:Perform a monkey patching of the class method. Differently from the first method, it changes the behavior of any instance of the class:
Create a class inherited from
testMOD
to override the method:You can monkey patch this method as follows:
output:
check class inheritance in python, to create your own custom class: