How do you monkeypatch a private method and still have access to the self
variable?
class Demo:
def __init__(self):
self.my_var = 12
def __my_private_method(self):
print(self.my_var)
demo = Demo()
demo._Demo__my_private_method()
# Prints: 12
# Monkey patching.
def __my_new_private_method(self):
print(self.my_var, 'patched!')
demo._Demo__my_private_method = __my_new_private_method
demo._Demo__my_private_method()
EDIT: While the question is indeed a duplicate, the original answer is too long (it's a whole tutorial).
SOLUTION: Access self
by using function.__get(object_instance)__
, where object_instance
is the instance of the object you want to monkeypatch.
demo._Demo__my_private_method = __my_new_private_method.__get__(demo)
demo._Demo__my_private_method()