Python is the first langauge I'm learning and currently I'm studying file input/output systems for storing simple data. I've briefly done an exercise regarding simple writing and pickling. For my purposes, I would like to use simple writing, as I would like to edit my "save files".
I have been successful in storing and retrieving data when the data is a STRING. The problem is when I store my object, it stores it as this unreadable format:
<__main__.Character object at 0x0078FE10>
How can I turn this unreadable format above back in to my object? Does Python have a built-in function that allows this?
Or will I have to convert my object to a string, containing all important variables BEFORE writing in to my data file?
Edit: Oops, forgot the code!
class Character(object):
def __init__(self,name,exp,atk):
self.name = name
self.exp = exp
self.lvl = int(self.exp/100)
self.health = 10
self.atk = atk
if atk == None:
self.atk = lvl*1.5
def stats(self):
print(self.name, end=" is level ")
print(self.lvl)
print("with", self.health, "health")
And here's the reading part of the I/O system. You can see it reads the data > converts the string to a list > splits arguments in list > use arguments for object creation.
with open('charData', 'r') as data:
data = data.read() # Read the contents of the file into memory.
print (data)
my_list = data.splitlines()
print (my_list[0]) # Print the list.
char_data = ast.literal_eval(my_list[0])
new_character = Character(*char_data)
Then I have my own function to display object stats:
new_character.stats()
spits out
Harley is level 3
with 10 health
so as you can see, it works fine. but if I use "newFile.write(new_character)" which is essentially the string of the object, which is "<main.Character object at 0x0215FE10>" from above.
I've been messing with str in the object for the past hour, but haven't found a way to use that function to find a solution and looking for guidance from a more experienced person.
Edit for Matt Habel:
def __str__(self):
print ("[\"", end="")
print (self.name, end="")
print ("\"", end=", ")
print (self.exp, end="")
print (",", end=" ")
print (self.atk, end="")
print ("]")
This outputs this:
["Harley", 300, 3]
print(new_character)
TypeError: __str__ returned non-string (type NoneType)
My reasoning for making my own "list" is so I can use the "AST" module to define the list arguments. I would later convert the list above to "new_character2", and write it using this:
newFile = open("charData","w")
newFile.write(new_character2)
Now I use:
Instead of that complicated parsing from above, I'm using the return function.
def export(self):
self.name = str(self.name)
self.exp = str(self.exp)
self.atk = str(self.atk)
matt_data = "[\"%s\", %s, %s]" % (self.name, self.exp, self.atk)
return matt_data
matt_export = new_character.export()
print(matt_export)
spits out:
["Harley", 600, 3]
and get no error code!