[英]How to load a class instance with Pickle (beginner backed into a pickle jar)
我已經經歷過以前的SO答案,但尚未找到答案。 我正在嘗試使用pickle保存和加載類實例,並且不斷收到錯誤消息:類型對象'Foo'沒有屬性'bar'。 我的代碼如下:
class Char:
name = "undefined"
def __init__(self, race, str, int, dex, con, spd, mp_bonus):
self.race = race
self.exp = 0
self.lvl = 1
self.str = str
self.int = int
self.dex = dex
self.con = con
self.spd = spd
self.hp = (con + str) / 2
self.current_hp = self.hp
self.mp_bonus = mp_bonus
self.mp = (int * mp_bonus)
self.current_mp = self.mp
def save(self):
with open("save.pk1", "wb") as fp:
pickle.dump(self.__dict__, fp, protocol=pickle.HIGHEST_PROTOCOL)
def load():
with open('save.pk1', 'rb') as fp:
Char.__init__ = pickle.load(fp) # no idea what to put here
# or if it should be in the Char class or not
def options(dude):
cls()
print("OPTIONS")
print("_____________________")
print("s. Save Game")
print("l. Load Game")
print("x. Quit Game")
print("_____________________")
select = input("please type in the corresponding letter or number: ")
if select == "s":
Char.save(player)
cls()
print("Save Complete")
wait()
main(dude)
elif select == "l":
cls()
print("Load Complete")
wait()
main(dude)
elif select == "x":
exit_screen(dude)
else:
print("you chose the wrong key")
wait()
main(dude)
def main(dude):
#menu as written in options above
select = input("please type in the corresponding letter or number: ")
if select == "s":
stats(dude)
elif select == "i":
inventory(dude)
elif select == "1":
rand_enemy()
elif select == "o":
options(dude)
else:
print("you chose the wrong key")
wait()
main(dude)
def start_screen(char):
#menu as written in options above
select = input("Please type in the corresponding number: ")
if select == "1":
get_char(char)
elif select == "2":
load()
main(char)
elif select == "3":
exit()
else:
print("you chose the wrong key")
wait()
start_screen(char)
start_screen(Char)
所以我的主要問題是,當我嘗試加載游戲時,它告訴我:AttributeError:類型對象'Char'沒有屬性'lvl'
雖然我聽不懂pk1文件,但是每次保存時都會對其進行更新,因此我知道保存功能可以正常工作。.我只是不確定如何獲取pk1文件中的信息並將其替換為Char。 在里面
我正在考慮只切換到JSON,因為我已經在代碼的其他部分中實現了它。.但是在這種情況下,我想通過使用pickle來簡化生活
您拋棄自我的方法。 dict對我來說似乎有點令人費解。 轉儲類Char的實例的常見方法如下:
class Char:
def save(self):
with open("save.pk1", "wb") as fp:
pickle.dump(self, fp, protocol=pickle.HIGHEST_PROTOCOL)
def load():
"""returns the saved instance of Char"""
with open('save.pk1', 'rb') as fp:
return pickle.load(fp)
為了清楚起見,我將添加上述類和方法的用法。
$ python -i 53796917.py
>>> c=Char()
>>> c.lvl = 10
>>> c.save()
>>>
$ python -i 53796917.py
>>> c=load()
>>> c.lvl
10
不拋出任何AttributeError
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.