Reputation: 175
import cPickle
class player:
level = 1
exp = 0
inven = []
char = player()
#Append items to char.inven later in program
def save():
file = open('savegame.dat', 'w')
cPickle.dump(char, file)
def load():
s_g = open('savegame.dat', 'r')
char = cPickle.load(s_g)
s_g.close()
This is a very small portion of the actual code, I cut it down to show where it's going wrong.
When I save/ load it, it doesn't keep the items in char.inven, even when I specifically dump the list into the file. Any idea why it erases the list's items?
Also, if I join the list before dumping it, it saves it. But some of the list items are 2 words, so list.split() makes it different from before
Upvotes: 1
Views: 273
Reputation: 251378
inven
is attribute of the class, not the instance. Pickle doesn't save anything about the class; it just stores the name of the class to reinstantiate it later. I would guess that you don't want inven
to be a class attribute anyway, so you should be doing:
class player:
def __init__(self):
self.level = 1
self.exp = 0
self.inven = []
Edit: if you are seeing that level
is saved, it's probably because you're rebinding it. If, for instance, you have code that does this:
self.level += 1
You are not incrementing the class attribute. You are creating a new instance attribute. Whenever you have an instance obj
and you do obj,attr = ...
you create an instance attribute, not a class attribute.
The reason you're not seeing the same effect with inven is because you're probably mutating it (e.g., with self.inven.append(...)
) rather than rebinding it. Thus you never create an instance attribute, you just keep modifying the class attribute.
You should search on StackOverflow for questions about class versus instance attributes (also sometimes called class and instance variables) to understand how this works in Python.
Upvotes: 3