object changing itself to another object

Kim Petersen kp at kyborg.dk
Thu Sep 26 04:28:34 EDT 2002

Glen Murphy wrote:
> I'm creating a program that takes user input, and passes it to an object -
> however, I want that object itself, and not the parent to change where 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()
> ### code end ###
> 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?

Terrible hack (but works for me...)

class Obj1:
     def key1(self):
         # do obj1 specific stuff
         print "Obj1"

You might want to make a "metamorphosis" __init__ that converts/creates
the variables needed in another class....

Just as a note: I needed this in Qt programming - since i couldn't 
change the autogenerated source's - and needed to subclass some of the 
Qt classes ... so i metamorph the autogenerated classes into mine 
instead ... which works - but i sure wish that there was a better way of 
telling the Designer what to do (or have a "smart" importer like the one 
in glade (where it loads the XML directly - and you can tell what 
classes a specific name must be - overriding the XML stuff...)

> Any help would be greatly appreciated,
> Cheers,
> Glen
> --
> Glen Murphy, http://glenmurphy.com/

More information about the Python-list mailing list