object changing itself to another object

Alex Martelli aleax at aleax.it
Thu Sep 26 09:08:36 EDT 2002


Glen Murphy wrote:
        ...
> that input goes. In the highly simplified example below, I would like the
> output to be "Obj1","Obj2","Obj1" - but not suprisingly, I just get Obj1,
> Obj1, Obj1
> 
> 
> ### code begin  ###
> 
> class Obj1:
>     def key1(self):
>         # do obj1 specific stuff
>         self = Obj2()
>         print "Obj1"
> 
> class Obj2:
>     def key1(self):
>         # do obj1 specific stuff
>         self = Obj1()
>         print "Obj2"
> 
> a = Obj1()
> 
> # simulate user keypresses
> a.key1()
> a.key1()
> a.key1()

Then change the classes to:

class Obj1:
    def key1(self):
        # do obj1 specific stuff
        self.__class__ = Obj2
        print "Obj1"

class Obj2:
    def key1(self):
        # do obj1 specific stuff
        self.__class__ = Obj1
        print "Obj2"



> I know I could achieve the result I want by doing horribly complicated
> trees of ifs and such, but I'd like my code to be nice and expandable (in
> this example, to easily add new Objs). I've looked through the Python FAQ,
> Google Groups and Various O'Reilly books, but I don't really know the
> terminology for what I'm looking for, so I haven't found anything so far,
> so does anyone have any pointers?

You have not checked O'Reilly's Python Cookbook, I think, because
this particular idea of changing an object's __class__ is exemplified
there.  http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/68429
in the online version, but I think you'll find the discussion more
complete, &c, in the printed version.


Alex




More information about the Python-list mailing list