Help with saving and restoring program state
mefjr75 at hotmail.com
Tue Jan 25 18:16:32 EST 2005
Jacob H wrote:
> Hello list...
> I'm developing an adventure game in Python (which of course is lots
I am glad you are having fun ,
after all life is so short,
isn't that what it is all about ;)
> One of the features is the ability to save games and restore the
> saves later. I'm using the pickle module to implement this. Capturing
> current program state and neatly replacing it later is proving to be
> trickier than I first imagined, so I'm here to ask for a little
> direction from wiser minds than mine!
> When my program initializes, each game object is stored in two places
> -- the defining module, and in a list in another module. The
> example is not from my actual code, but what happens is the same.
> (code contained in "globalstate" module)
> all_fruit = 
> (code contained in "world" module)
> class Apple(object): # the class hierarchy goes back to object,
> def __init__(self):
> self.foo = 23
> self.bar = "something"
> apple = Apple()
Ok here is a guess. (I recently did something similar, maybe this will
If you already knew about this stuff then just ignore me :)
You have defined a class for your objects, which is a nifty
The apple class can also keep track of the total amount of apple
instances handed out.
Sometimes it is better to let the objects handle there own state.
Py> class Apple(object):
... total = 0 # this is a 'class variable' shared by all instances
... def __init__(self):
... self.__class__.total += 1
... self.foo = 23 # this is an 'instance variable/name'
... self.bar = "something"
... apple = Apple()
... apple_two = Apple()
... print apple_two.total
... apple_three = Apple()
... print apple.total
... print apple_three.total
Now you can just pickle them and when you unpickle them as usual.
Also another idea is to use a class instead of a global.
I'll admit it I have a personal distaste for them, but classes work so
well I never miss them.
Now just create an instance and add your attributes.
Py>store = Store()
...store.color = 'red'
...store.height = 5.7
...store.secret = 42
And get them back when needed.
More information about the Python-list