Add methods to a class at runtime?

Robert Oschler Oschler at
Sun Sep 1 13:17:56 EDT 2002

"Gerhard Häring" <gerhard.haering at> wrote in message
news:slrnan4dl3.18h.gerhard.haering at
> >>> class Foo: pass
> ...
> >>> foo = Foo()
> >>>
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> AttributeError: Foo instance has no attribute 'bar'
> >>> def bar(self): print "bar"
> ...
> >>> = 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?


More information about the Python-list mailing list