Python: override base class

I am looking at changing the behavior of some third-party Python codes. There are many classes derived from the base class, and in order to easily achieve my goal, it would be easiest to override the base class used to get all the other classes. Is there an easy way to do this without having to touch any third code? In case I could not clearly explain this:

class Base(object): '...' class One(Base) '...' class Two(Base) '...' 

... I would like to make changes to Base without actually changing the above code. Perhaps something like:

 # ...code to modify Base somehow... import third_party_code # ...my own code 

Python may have a great built-in solution to this problem, but I still don't know about it.

+4
source share
1 answer

Perhaps you can defuse methods in 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() 

Will print

 original foo original foo monkey-patched foo monkey-patched foo 
+5
source

All Articles