I understood how to replace methods at run time in Python by going through these links.[ Link1 , Link2 , & Link3].
When I replaced a "update_private_variable" method of class A, its getting replaced but its not updating the private variable.
import types
class A:
def __init__(self):
self.__private_variable = None
self.public_variable = None
def update_private_variable(self):
self.__private_variable = "Updated in A"
def update_public_variable(self):
self.public_variable = "Updated in A"
def get_private_variable(self):
return self.__private_variable
class B:
def __init__(self):
self.__private_variable = None
self.public_variable = None
def update_private_variable(self):
self.__private_variable = "Updated in B"
def update_public_variable(self):
self.public_variable = "Updated in B"
When calling the method without replacement:
a_instance = A()
a_instance.update_private_variable()
print(a_instance.get_private_variable())
#prints "Updated in A"
When calling the method after replacement:
a_instance = A()
a_instance.update_private_variable = types.MethodType(B.update_private_variable, a_instance)
a_instance.update_private_variable()
print(a_instance.get_private_variable())
#prints None
Whereas replacing and calling a method which updates public variable, works fine
a_instance = A()
a_instance.update_public_variable = types.MethodType(B.update_public_variable, a_instance)
a_instance.update_public_variable()
print(a_instance.public_variable)
#prints 'Updated in B'
Is there any other way to replace method of an instance at runtime, so that private attributes gets updated by invoking replaced method?