Add methods to a class at runtime?

Emile van Sebille emile at fenx.com
Sun Sep 1 18:55:04 CEST 2002


"Gerhard Häring" <gerhard.haering at gmx.de> wrote in message
news:slrnan4dl3.18h.gerhard.haering at lilith.my-fqdn.de...
> Robert Oschler wrote in comp.lang.python:
> > [Glyph said:]
> > "One of the eye-popping cool features of Python is the ability to
> > change code and have existing instances update to use the new
> > methods automatically. "
> >
> > Can someone point me to a code snippet shows how to do this?
>
> >>> 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
>

You can also use new.instancemethod to add a method to an specific instance:

Python 2.1.3 (#35, Apr  8 2002, 17:47:50) [MSC 32 bit (Intel)] on win32
Type "copyright", "credits" or "license" for more information.
>>> class Foo: pass
...
>>> foo=Foo()
>>> fee=Foo()
>>> def bar(self): print 'bar'
...
>>> import new
>>> fee.bar = new.instancemethod(bar, fee, Foo)
>>> fee.bar
<method Foo.bar of Foo instance at 0088018C>
>>> fee.bar()
bar
>>> foo.bar
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
AttributeError: Foo instance has no attribute 'bar'


Emile van Sebille
emile at fenx.com









More information about the Python-list mailing list