[Tutor] define vars by iteration

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Thu Oct 20 21:31:45 CEST 2005



>  Also, I have done what I'm trying to do successfully by populating a
> dictionary with class instances named after self.name <http://self.name>,
> which, after the function runs, I can access this way
>  >>> classDictionary["Yard"]
> <class instance>
>  the thing is I would like to be able to get at Yard's attributes by typing
>  >>> Yard.anAttribute
> garbage cans
>  at the prompt rather than
>  >>> Yard = classDictionary["Yard"]
> >>> Yard.anAttribute
> garbage cans


Hi Luke,

One thing to note is that we can formally plunk and embed these places in
some kind of World:

######################################################
class World:
    def __init__(self):
        self.places = {}
    def attach(self, place):
        """Given a place, attaches it to the world."""
        self.places[place.name] = place
    def lookup(self, name):
        return self.places[name]
######################################################


If each place was aware that it was a part of a world --- that is, if we
embed the World inside each place as a part of a place's state --- then
things might work out.

For example, we might have a north-south corridor:

##################################################################
class Corridor:
    def __init__(self, world, name, northName, southName):
        self.world, self.name, self.northName, self.southName = (
            world, name, northName, southName)
    def N(self):
        return self.world.lookup(self.northName)
    def S(self):
        return self.world.lookup(self.southName)
##################################################################

What's a little funny about this Corridor definition is that, because a
cooridor knows its in the world, it can also ask the world what place
'northName' stands for in its N() method.


Here's a small test:

######
>>> world = World()
>>> world.attach(Corridor(world, "Water cooler",
...                       north="Stairs", south="Boss Office"))
>>> world.attach(Corridor(world, "Stairs",
...                       north="Wall", south="Water cooler"))
>>>
>>>
>>> world.lookup("Water cooler")
<__main__.Corridor instance at 0x403a7fcc>
>>> world.lookup("Water cooler").name
'Water cooler'
>>> world.lookup("Water cooler").N()
<__main__.Corridor instance at 0x403a7f6c>
>>> world.lookup("Water cooler").N().name
'Stairs'
######

Another advantage of having a central place is that saving and restoring
the environment is just a matter of pickling the world.  Hmmm... briny
pickles... *grin* Sorry, I'm getting distracted by food.


Does this make sense?  Please feel free to ask more questions.



More information about the Tutor mailing list