首页 > 解决方案 > 将类保存和加载到文件

问题描述

我正在制作一个基于文本的游戏来更好地学习 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)

提前致谢。

标签: pythonclasspickle

解决方案


推荐阅读