I wish to modify the method of a class by changing its behaviour. Please note that I do NOT wish to rewrite another method altogether as it is complex and involves many variables and interacts with other methods. Here is an example of what I'm trying to do:
import types
class example_class(object):
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
self.pi = 3.14
def example_method(self):
print(self.a * self.b * self.c * self.pi)
#Create an instance of the object and call the method.
my_example = example_class(3, 5, 7)
my_example.example_method()
#Now I wish to change the "example_method" to add instead of multiply.
def different_method(self, a, b, c):
print(self.a + self.b + self.c + self.pi)
my_example.example_method() = types.MethodType(different_method(10,20,30), my_example)
I tried using types.MethodType but the above does not work. Note that I am trying to replace the example.method() with different.method(). I would like to give the method different values to calculate as well.
EDIT: Thank you to all who answered my question! You have clarified it for me and now I can monkeypatch my classes! However, I should have clarified further. I wished to modify my method to include yet another variable. So my different_method should be like this:
#Now I wish to change the "example_method" to add instead of multiply.
def different_method(self, a, b, c, extra_variable):
print(self.a + self.b + self.c + extra_variable + self.pi)
I am having difficulty adding the extra variable-if you could provide some guidance on that, I’d be very grateful!
my_example.example_method = ...(no parens, as it's not an invocation, it's a reference).