python - 将类保存和加载到文件
问题描述
我正在制作一个基于文本的游戏来更好地学习 python。我做了一些类,我想为游戏编写一个保存状态。我可以将每个类的每个属性单独写入/读取到一个文件中,但显然这很麻烦。我用过pickle,但我在不同的函数中有保存/加载,所以pickle在函数中工作,但是当它回到主函数时,类恢复到加载之前。所以有两个问题:1.有没有办法防止班级使用泡菜恢复?或2:有没有办法简化file.write(class)
?
这是我一直在测试的代码。我已经简化了 main,因此可以很容易地更改属性并检查负载是否正常工作。
class game:
def __init__(self, position, coins):
self.position = position
self.coins = coins
player = game("start", 10)
#save w/ pickle - works
def save():
save = input("Enter name: ")
with open(save + ".txt", "wb") as file:
pickle.dump(player, file)
#save w/o pickle - works, would require a LOT of code
def save():
save = input("Enter name: ")
with open(save + ".txt", "w") as file:
file.write(player.position)
#file.write(<other attributes>)
#load w/ pickle - player class doesn't transfer out of function
def load():
try:
load = input("Enter name: ")
with open(load + ".txt", "rb") as file:
player = pickle.load(file)
print(player.position)
print(player.coins)
except FileNotFoundError:
print("File doesn't exist.")
#load w/o pickle - works, would require a LOT of code
def load():
try:
load = input("Enter name: ")
with open(load + ".txt", "rb") as file:
player.position = file.read()
#will need to modified to read each line separately
print(player.position)
print(player.coins)
except FileNotFoundError:
print("File doesn't exist.")
a = ""
while a.lower() != "exit":
a = input("Enter input: ")
if a.lower() == "save":
save()
elif a.lower() == "load":
load()
elif a.lower() == "p":
player.position = "pond"
print(player.position)
elif a.lower() == "b":
player.position = "bridge"
print(player.position)
elif a.lower() == "s":
player.position = "start"
print(player.position)
elif a.lower() == "print":
print(player.position)
print(player.coins)
elif a.lower() == "-":
player.coins -= 1
print(player.coins)
提前致谢。
解决方案
推荐阅读
- c# - 从同一任务的 ContinueWith 方法启动任务是否安全?
- scala - 没有可用的同步实例时如何运行 FS2 流?
- meshlab - MeshLab 简化边缘塌陷算法?
- android - Android 应用程序在 onPostExecute() 中崩溃,没有任何错误
- datatables - Datatable获取点击行上的数据属性
- php - 在 Codeigniter 中添加两个输入值作为字符串
- excel - 从 Excel VBA 在 Word 中编写项目符号列表
- git - 设置 kde 后如何使用来自 github 的 homebrew-kde 在 Macos 上安装 Kdevelop
- android - SignalStrength 在 api 25 中没有方法 getRsrq
- asp.net - 如何判断服务是否已被垃圾收集