Adding new methods at runtime to a class
eppstein at ics.uci.edu
Mon Nov 24 23:15:37 CET 2003
In article <roy-A5FC3C.16223824112003 at reader2.panix.com>,
Roy Smith <roy at panix.com> 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 foo.bar doesn't have to exist until the moment
> it's evaluated, why should foo.bar() have to? Or maybe a better way to
> ask it is why should foo.bar have to be callable at any other time than
> when you evaluate foo.bar()?
> 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
>>> def printme(self): print "I am " + repr(self) + "."
>>> foo.method = printme
I am <__main__.foo instance at 0x40aa8>.
And, just to verify that it really is a method and not just a function:
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 http://www.ics.uci.edu/~eppstein/
Univ. of California, Irvine, School of Information & Computer Science
More information about the Python-list