Adding new methods at runtime to a class

Michele Simionato mis6 at pitt.edu
Tue Nov 25 01:47:19 EST 2003


François Pinard <pinard at iro.umontreal.ca> wrote in message news:<mailman.1051.1069730953.702.python-list at python.org>...
> [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! :-)

I was thinking about an even more frightening possibility: changing the
class of the stateful object! I.e. there would be a different class
for each state (hopefully collected in a common hierarchy) and one
would change the class of "self" according to some condition. This
would automatically accomplish the change of the methods according
to the state, and would give the additional benefit of inheritance
(i.e. methods could call they supermethods quite easily).

I haven't written anything yet, since I am not sure if it would be
a good idea in practice, however I wonder if somebody ever tried it.

The message is "We got a dynamic language: let use it!"

                  Michele




More information about the Python-list mailing list