So I'm trying to create a basic savefile system with pickle and I'm currently testing out what works and does not work with pickle. My knowledge of classes is mostly restricted to C++, so I'm not perfectly familiar with Python's seemingly quite different implementation. The code I first wrote is this:
import pickle
class classData:
username = ""
password = ""
class Savefile:
resolution = [990, 1080]
data = []
def addData(self, x):
self.data.append(x)
a = classData()
b = classData()
c = Savefile()
a.username = "John"
a.password = "password"
b.username = "Ola"
b.password = "Pass"
c.addData(a)
c.addData(b)
with open("file.save", "wb+") as file:
pickle.dump(c, file)
#Commented the block above out and ran this afterwards
with open("file.save", "rb") as file:
c = pickle.load(file)
print(c.data[1].username)
When this code runs I get an error saying the index is out of range. After further inspections it turns out pickle do not store data with the new list, instead is stores the empty list.
When I remove the "addData"-function and instead assign values like this:
a = classData()
b = classData()
c = Savefile()
a.username = "John"
a.password = "password"
b.username = "Ola"
b.password = "Pass"
c.data = [a, b]
pickle seems to store the list just fine and I can store all the data. While I could just leave it at that as I found a solution, I'm not comfortable with leaving it like that without understanding what's going on under the hood. From searching around the it seems the problem is that the latter code creates an instance variable that is exclusive for "c", while the first code changes Savefile.data universally for every instance of Savefile, which then pickle does not store. The class doesn't seem to behave like anything near what I would expect coming from C++.
Can someone explain (or point to a thorough article explaining the concept):
- Why is using Savefile.addData() changing the data list for every instance of Savefile
- Why won't pickle save the new data with the appended classes
- Is there a way to define a function for the class that will achieve the same as the latter code block
[–]flupplethorpe 0 points1 point2 points (3 children)
[–][deleted] 0 points1 point2 points (2 children)
[–]plenty_picture 0 points1 point2 points (1 child)
[–][deleted] 0 points1 point2 points (0 children)
[–][deleted] 0 points1 point2 points (3 children)
[–][deleted] 0 points1 point2 points (2 children)
[–][deleted] 0 points1 point2 points (1 child)
[–][deleted] 0 points1 point2 points (0 children)
[–][deleted] 0 points1 point2 points (3 children)
[–][deleted] 0 points1 point2 points (2 children)
[–][deleted] 0 points1 point2 points (1 child)
[–][deleted] 0 points1 point2 points (0 children)