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?
a_instance.update_private_variable()after rebindingupdate_private_variable.TypeError: unbound method update_private_variable() must be called with B instance as first argument (got A instance instead)Also there is no actual public/private system.public_variableand__private_variableare both as accessible to the user as each other.__leading_double_underscoreattribute name - use a_leading_single_underscoreto indicate private-by-convention, and reserve the double for avoiding name conflicts between subclasses._leading_single_underscore, it works properly. But as per my requirement, i can't change the "naming convention"