Add methods to a class at runtime?

Peter Hansen peter at engcorp.com
Sun Sep 1 13:36:52 EDT 2002


Robert Oschler wrote:
> 
> "Gerhard Häring" <gerhard.haering at gmx.de> wrote:
> > >>> def bar(self): print "bar"
> > ...
> > >>> Foo.bar = bar
> > >>> foo.bar()
> > bar
> 
> Thanks but I need a little bit more detail.  Suppose I want to do it from
> within code?  For example, I create a function called
> AddBarToFoo(FooObject), that given a object of type Foo (FooObject) adds the
> Bar method to it dynamically, what would be the syntax then?  Would I have
> to put the method declaration code, which you show being typed in to the
> interpreter, in a string and then eval/exec it?  Is there a more convenient
> way than that?

Robert, pretty much anything you can type at the interactive prompt
can be typed as-is into a source file and executed the same way.
That's why the prompt is so good for experimenting and learning.
Try doing what you want interactively, the way Gerhard did, and then
in your text editor window paste in the bits of code as you get
them working.

Basically, to do what you are asking you shouldn't have to do
anything different than what Gerhard did, but there's no substitute
for trying it yourself.  (If you have troubles, show us some 
snippets that you've tried so we can get a better idea where
you are trying to do with this.)

-Peter



More information about the Python-list mailing list