overwriting method in baseclass

Steven Bethard steven.bethard at gmail.com
Mon Feb 7 01:52:59 EST 2005


Harald Massa wrote:
> Hello!
> 
> I am using a library (= code of so else) within Python. Somewhere in this 
> library there is:
> 
> class foo:
>     	def baa(self, parameters):
>          print "something"
>          self.baazanan(some other parameters)
> 
> 
> class mirbo(foo):
>       def baazanan(self, lalala):
>           print "heylo tada"
> 
> class fujiko(foo):
>       def baazanan(self, ltara):
>           print "sing a song with me"
> 
> 
> ....
> 
> 
> now I want to change the common baa-method. so that
> 
> def baa(self, parameters):
>       print "soemthing special"
>       self.baazanan(some other parameters)
> 
> Of course, I use a Python- and GPL-Licence compatible library, I can 
> change the source of foo, and use my changed library.
> 
> But someday, it happened before, there will be an update by the publisher 
> to that library.... and I have to do all again.
> 
> So, what is the most elegant solution to administer these changes? 

Given these classes:

py> class foo:
...     def baa(self):
...         print "something"
...         self.baazanan()
...
py> class mirbo(foo):
...     def baazanan(self):
...         print "heylo tada"
...
py> class fujiko(foo):
...     def baazanan(self):
...         print "sing a song with me"
...

You should be able to redefine the method and assign it to the foo class:

py> def new_baa(self):
...     print "soemthing special"
...     self.baazanan()
...
py> foo.baa = new_baa

Then any instances created after this assignment should use the new baa 
method you defined:

py> mirbo().baa()
soemthing special
heylo tada
py> fujiko().baa()
soemthing special
sing a song with me

You also might bring up this point to the maintainer of the library -- 
if they know your intents, they can make this easier for you...

STeVe



More information about the Python-list mailing list