Search code examples
pythonooppython-3.xselfmonkeypatching

Why don't monkey-patched methods get passed a reference to the instance?


See this example for a demonstration:

>>> class M:
       def __init__(self): self.x = 4
>>> sample = M()
>>> def test(self):
        print(self.x)
>>> sample.test = test
>>> sample.test()
Traceback (most recent call last):
  File "<pyshell#17>", line 1, in <module>
    sample.test()
TypeError: test() missing 1 required positional argument: 'self'

Why?


Solution

  • The test method you are assigning to sample.test is not bound to the sample object. You need to manually bind it like this

    import types
    sample.test = types.MethodType(test, sample)
    sample.test()
    # 4