So I have a list of defined classes that gets exported on the exit of the program.. and it looks like this:
<__main__.Block object at 0x02416B70>,
<__main__.Block object at 0x02416FF0>,
<__main__.Block object at 0x0241C070>,
<__main__.Block object at 0x0241C0D0>,
<__main__.Block object at 0x0241C130>,
<__main__.Block object at 0x0241C190>,
<__main__.Block object at 0x02416DF0>,
<__main__.Block object at 0x0241C250>,
<__main__.Block object at 0x0241C2B0>,
<__main__.Block object at 0x0241C310>,
<__main__.Block object at 0x0241C370>,
<__main__.Block object at 0x0241C3D0>,
<__main__.Block object at 0x0241C430>,
<__main__.Block object at 0x0241C490>,
<__main__.Block object at 0x0241C4F0>,
<__main__.Block object at 0x0241C550>,
<__main__.Block object at 0x0241C5B0>,
<__main__.Block object at 0x0241C610>
Perfect! Right? Now I should easily be able to convert that to a list.. So I use this:
x=x.split(",")
And it converts it to a list yes, but it turns the classes into strings! Making them un-usable.
Basically what I need is to "suspend" the state of the game within a file when it is closed, and then reload it upon opening it.
So how can I do this without converting the class names to strings?
Sadly, no. What you see here (
<__main__.Block object at 0x02416B70>
) is a typical string representation of a class instance. It's just a simple string, and there's no way to convert this string back to an instance of ofBlock
.I assume you're still on this game from your last question.
So how do you actually persist the state of the game? The easiest way is to use the standard python module
pickle
orshelve
.In the following example, I'll use
shelve
, because you don't use a single class to represent the game state:First of all, when we exit the game, we want to save the player and the blocks, so let's call a new
save
function when the game is about to exit:The implementation is quite easy (no error handling for brevity):
As you see, using
shelve
is as easy as using adict
.Next step is loading our saved data.
We call a new function
load
which will either return a tuple of the saved player object and a list of the saved block objects, orNone
. In case ofNone
, we don't create a player yet and use an empty list for our blocks.The implementation is as simple as the
save
functon:And that's it.
Here's the complete code:
And here you can see loading and saving in action:
Note that you can't save (or "pickle")
Surfaces
this way. In this code, it works because theSurfaces
ofPlayer
andBlock
are class variables, not instance variables, and thus don't get saved to disk. If you want to "pickle" an object with aSurface
instance variable, you would have to remove theSurface
first (e.g. setting it toNone
) and load it again (e.g. in theload
function).