AttributeError when monkey patching an object in python
Question: I tried to monkey patch an object in Python.

    
    
    class C:
        def __init__(self):
            self.__n = 0
    
        def f(self):
            self.__n += 1
    
        def __str__(self):
            return str(self.__n)
    
    
    c = C()
    
    def up(self):
        self.__n += 2
    
    import types
    c.up = types.MethodType(up, c)
    c.up()
    

But I got an AttributeError

    
    
    Traceback (most recent call last):
      File "untitled4.py", line 19, in <module>
        c.up()
      File "untitled4.py", line 15, in up
        self.__n += 2
    AttributeError: 'C' object has no attribute '__n'
    

How can I fix the error?


Answer: As your `up` function isn't declared inside a class, it is not possible to
apply [name
mangling](https://docs.python.org/3.5/tutorial/classes.html#private-variables)
rules to its locals, while it is applied for the attribute name. Therefore
you'd need to apply the name mangling manually in your function:

    
    
    def up(self):
        self._C__n += 2
    

