object changing itself to another object
Eric Brunel
eric.brunel at pragmadev.com
Thu Sep 26 04:22:04 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?
AFAIK, there's no way to do exactly what you request. In fact, I've never
seen a language allowing to dynamically change the class of an object once
it's been created. But there's a quite simple workaround using a factory
object. For example:
class Obj1:
...
class Obj2:
...
class ObjFactory:
def __init__(self):
self.__theClasses = [Obj1, Obj2]
self.__classIndex = 0
self.__theObject = None
def getObject(self):
self.nextObject()
return self.__theObject
def nextObject(self):
self.__theObject = self.__theClasses[self.__classIndex]
self.__classIndex = (self.__classIndex + 1) / len(self.__theClasses)
And now, it does what you want:
a = ObjFactory()
a.getObject().key1() # Called on Obj1
a.getObject().key1() # Called on Obj2
a.getObject().key1() # Called on Obj1
I don't know if it suits your needs exactly, but you get the idea... And
since the actual objects are created by the factory, you can make them know
the factory and call themselves the nextObject method when needed instead
of calling it systematically in getObject.
HTH
--
- Eric Brunel <eric.brunel at pragmadev.com> -
PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com
More information about the Python-list
mailing list