dynamically extend classes

Gordon McMillan gmcm at hypernet.com
Sat Feb 19 16:14:01 EST 2000


Matt Wette wrote:
 
> Is there a way to dynamically extend classes in Python?
> 
> I'd like to be able to have sitecustomize.py import a module
> and add methods to a class so that later, when anohter modules
> imports this module and uses the class it sees the added methods.
> 
> Doable?

Oh yeah.

class MyAddedMethods:
  def snarf(self):
   ...

import innocent
bases = innocent.Sucker.__bases__
innocent.Sucker.__bases__ = bases + (MyAddedMethods,)
print "Come on in, dear, the water's fine!"
import sound
sound.play('Theme_from_Jaws')

- Gordon




More information about the Python-list mailing list