Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: override base class

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.

like image 872
Captain Midday Avatar asked Nov 25 '12 10:11

Captain Midday


1 Answers

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
like image 108
NPE Avatar answered Nov 05 '22 12:11

NPE