Python: replacing a function within a class of a module

后端 未结 3 1193
遥遥无期
遥遥无期 2020-12-13 11:35

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 befor

3条回答
  •  伪装坚强ぢ
    2020-12-13 11:43

    You can monkey patch this method as follows:

    class TestMOD(object):
    
        def testFunc(self, variable):
            var = variable
            self.something = var + 12
            print(f'original {self.something}')
    
    
    def alternativeFunc(self, variable):
        var = variable
        self.something = var + 1.2
        print(f'alternative {self.something}')
    
    
    if __name__ == '__main__':
    
        test_original = TestMOD()
        test_original.testFunc(12)
    
        TestMOD.testFunc = alternativeFunc
    
        test_alternate = TestMOD()
        test_alternate.testFunc(12)
    

    output:

    original 24
    alternative 13.2
    

提交回复
热议问题