Adding new methods at runtime to a class

Michael Hudson mwh at python.net
Tue Nov 25 12:45:30 CET 2003


mis6 at pitt.edu (Michele Simionato) writes:

> 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!"

I *think* I'd rather change an attribute of the instance for each
state change and forward onto that:

    def move_state(self):
        self.state = State()

    def do_something_dependent_on_state(self):
        self.state.do_something()

Cheers,
mwh

-- 
  Premature optimization is the root of all evil.
       -- Donald E. Knuth, Structured Programming with goto Statements




More information about the Python-list mailing list