Add methods to a class at runtime?
Robert Oschler
Oschler at earthlink.net
Sun Sep 1 13:17:56 EDT 2002
"Gerhard Häring" <gerhard.haering at gmx.de> wrote in message
news:slrnan4dl3.18h.gerhard.haering at lilith.my-fqdn.de...
> >>> class Foo: pass
> ...
> >>> foo = Foo()
> >>> foo.bar()
> Traceback (most recent call last):
> File "<stdin>", line 1, in ?
> AttributeError: Foo instance has no attribute 'bar'
> >>> def bar(self): print "bar"
> ...
> >>> Foo.bar = bar
> >>> foo.bar()
> bar
> >>>
Gerhard,
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?
thx
More information about the Python-list
mailing list