Let's say I have a class, FooClass, that has a method, foo_method, defined. This class is in a third party library, and I want to explicitly override it. I have a number of classes that inherit from FooClass, so I don't want to override foo_method for every single subclass. Instead, I'd like to override the class's method definition without digging into the third party library code. When I try the obvious way,
from thirdparty import FooClass
class FooClass(object):
def foo_method():
newstuff
I get strange behavior -- NotImplementedErrors and such. Am I missing something?
You are redefining the class locally; that won't change the original class or affect anyone using it elsewhere.
You can monkeypatch the method on the class:
from thirdparty import FooClass
orig_foo_method = FooClass.foo_method
def new_foo_method(self):
# do new stuff
# perhaps even call orig_foo_method(self)
FooClass.foo_method = new_foo_method
Now any code that tries to call .foo_method() on instances of FooClass anywhere in your Python interpreter will find and call your new_foo_method() method instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With