I'm looking at modifying the behavior of some 3rd party Python code. There are many classes derived from a base class and in order to easily achieve my goal, it'd be easiest just to override the base class used to derive all the other classes. Is there a simple way to do this without having to touch any of the 3rd party code? In case I've failed to clearly explain this:
class Base(object):
'...'
class One(Base)
'...'
class Two(Base)
'...'
...I wold like to make modifications to Base
without actually modifying the above code. Perhaps something like:
# ...code to modify Base somehow...
import third_party_code
# ...my own code
Python probably has some lovely built-in solution to this problem, but I'm not yet aware of it.
Perhaps you could monkey-patch the methods into Base
?
#---- This is the third-party module ----#
class Base(object):
def foo(self):
print 'original foo'
class One(Base):
def bar(self):
self.foo()
class Two(Base):
def bar(self):
self.foo()
#---- This is your module ----#
# Test the original
One().bar()
Two().bar()
# Monkey-patch and test
def Base_foo(self):
print 'monkey-patched foo'
Base.foo = Base_foo
One().bar()
Two().bar()
This prints out
original foo
original foo
monkey-patched foo
monkey-patched foo
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