0

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()

enter image description here

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()
Florian Fasmeyer
  • 795
  • 5
  • 18
  • Please keep in mind that [these are not "private" methods and have relatively limited actual purpose](https://stackoverflow.com/questions/7456807/python-name-mangling). – Karl Knechtel May 01 '22 at 14:44
  • @mkrieger1 no, the entire point of the question is that the standard approach apparently fails (I can reproduce it) with name-mangled methods. – Karl Knechtel May 01 '22 at 14:45
  • If you change the private method on the class, it will work: `setattr(Demo, '__my_private_method', __my_new_private_method)` – Christopher Peisert May 01 '22 at 14:56

0 Answers0