Adding new methods at runtime to a class

David Eppstein eppstein at
Mon Nov 24 23:15:37 CET 2003

In article <roy-A5FC3C.16223824112003 at>,
 Roy Smith <roy at> wrote:

> > Before we send you into what most would consider black magic in Python, you 
> > should explain why you want to.
> > 
> > In most cases, this is *not* what you want to do - there are better, more 
> > elegant and much more Pythonic ways of doing it.
> > 
> > Tim Delaney
> > 
> Why is it unpythonic to add methods at runtime?  That's the nature of a 
> dynamic language.  If doesn't have to exist until the moment 
> it's evaluated, why should have to?  Or maybe a better way to 
> ask it is why should have to be callable at any other time than 
> when you evaluate
> I would say that the fact that all of a class's methods have to be 
> declared at once is itself somewhat unpythonic.

Black magic?  It's not very difficult...

>>> class foo:pass
>>> f=foo()
>>> def printme(self): print "I am " + repr(self) + "."
>>> foo.method = printme
>>> f.method()
I am < instance at 0x40aa8>.

And, just to verify that it really is a method and not just a function:

>>> foo.method(1)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: unbound method printme() must be called with foo instance as 
first argument (got int instance instead)

Ok, the error message doesn't use the right name but in other respects 
it works as you would expect.

David Eppstein            
Univ. of California, Irvine, School of Information & Computer Science

More information about the Python-list mailing list