object changing itself to another object

John Roth johnroth at ameritech.net
Thu Sep 26 16:15:38 CEST 2002


"Glen Murphy" <abuse at nospam.riot.com.au> wrote in message
news:amu0lv$6ac$1 at otis.netspace.net.au...
> 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?
>
> Any help would be greatly appreciated,
> Cheers,
> Glen
>
> --
> Glen Murphy, http://glenmurphy.com/

It's a standard pattern, check out the Patterns book. Unfortunately, my
copy is in a storage locker on the other end of the continent, so I
can't
give you the name off the top of my head.

What it requires (I believe) is a level of indirection. The top level
is essentially a Facade that calls the real object. You can then change
the real object to anything you want as long as it understands the
method calls the Facade object makes.

John Roth

John Roth
>
>





More information about the Python-list mailing list