Created
August 20, 2025 18:34
-
-
Save cgoldberg/57d6d438b463840c3a97d4d5dca3b9df to your computer and use it in GitHub Desktop.
Python - monkeypatch a method on a class and call the original method from the new one
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# | |
# monkeypatch a method on a class and call the original method from the new one | |
from functools import partialmethod | |
class MyClass: | |
# this is the original method | |
def my_method(self): | |
print("hello from the original method") | |
# this is a function that replaces the original method | |
def my_method(self, orig): | |
print("hello from the replacement method") | |
# orig here is the original method, so can be called like this: | |
orig(self) | |
# this makes the function a method on the class | |
MyClass.my_method = partialmethod(my_method, MyClass.my_method) | |
# example usage | |
if __name__ == "__main__": | |
foo = MyClass() | |
foo.my_method() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment