dynamically extend classes

Terry Reedy tjreedy at udel.edu
Sat Feb 19 16:05:08 EST 2000


"Matt Wette" <Matthew.R.Wette at jpl.nasa.gov> wrote in message
news:7kwvo1mbam.fsf at jpl.nasa.gov...

[posted and emailed]

> 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?

According to doc, yes.  Try an appropriate version of the following
(untested).

Let mymodule.py consist of
myclass: pass #or whatever

Add the following to sitecustomize.py:

def mymethod(self, arg): pass #do whatever
inport mymodule
mymodule.myclass.mymethod = mymethod

Mymethod is now a method of myclass just the same as if the def were instead
in mymodule.py indented under the class definition.

Terry J. Reedy










More information about the Python-list mailing list