3

I'm trying to change the method of class on the fly. I can change it using the class name, like here:

class Foo:
    def __init__(self, x):
        self.x = x

    def method(self):
        print("original method")
        return self.x


def new_method(self):
     print("new method")
     return self.x

Foo.method = new_method
foo = Foo(1)
print(foo.method())  # Works fine

But I'd like to change the method using the object name, not the class, and it raises an error:

foo = Foo(1)
foo.method = new_method
print(foo.method())  # TypeError: new_method() missing 1 required positional argument: 'self'

Would appreciate any help on this matter

1 Answer 1

6

You need to provide the binding for self. This is done automatically for you when a method is defined in a class, but not when you monkey-patch an object.

>>> foo = Foo(1)
>>> foo.method = lambda: new_method(foo)
>>> print(foo.method())
new method
1
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.