Adding new methods at runtime to a class

François Pinard pinard at iro.umontreal.ca
Mon Nov 24 22:28:37 EST 2003


[Delaney, Timothy C (Timothy)]
> > From: Fernando Rodriguez

> > How can I add new methods at runtime to a class?

> 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.

There is a case which happens sometimes for me, in which I find it
useful assigning methods at runtime.  It occurs in stateful objects,
where the actions of conceptual method varies according to the state.
It is clean, clear and fast to merely assign various processors to
methods when the state changes, more than maintaining and testing a
state variable all-around in a never changing set of methods.  (What
does not change is the external API.)

To me at least, it does not look like black magic, I find it Pythonic
enough, and even elegant, to the point I'm doing more and more.  Oh, I
do read your assertion about what people do "in most cases", but I'm not
sure how you get such statistics.  Please enlighten us! :-)

-- 
François Pinard   http://www.iro.umontreal.ca/~pinard





More information about the Python-list mailing list