bob gailer wrote:
> ------------ Python coding "trick"1 ------------ > when I build a map I omit the () after the class e.g. 'death' = Death, > ... and apply them to the item retrieved from the map. > > use a decorator to build the map dictionary: > > # the decorator function: > def add_to_map(cls, map={}): # map is initialized to a {} when function > is "compiled" > if cls: > map[cls.__name__] = cls # add entry to dictionary > return cls > else: return map > > # apply decorator to class definitions > # this will add 'Death': <class '__main__.Death'> > @add_to_map > class Death(Scene): > class_definition > > # ditto for all other classes based on Scene - then > > class Map: > scenes = add_to_map() # note when map is called with no arguments > it returns the dictionary Hm, you have now replaced the dead simple > class Map(object): > scenes = { > 'central_corridor': CentralCorridor(), > 'laser_weapon_armory': LaserWeaponArmory(), > 'the_bridge': TheBridge(), > 'escape_pod': EscapePod(), > 'death': Death() > } with a class decorator, a dunder name, a mutable default argument -- lots of clever Python specific stuff that I wouldn't put on a beginner's list of top priorities. Don't use unless you spotted at least one bug in the code sample at first glance :) By the way, you do not need a map (dict) at all to implement a game like this, you may return the next scene directly. A sketch: class Bridge: def enter(self): ... action = ... if action == "jump off the bridge": return Death("You are eaten by the piranhas") else: ... _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor