【问题标题】:How to load a class instance with Pickle (beginner backed into a pickle jar)如何使用 Pickle 加载类实例(初学者支持 pickle jar)
【发布时间】:2018-12-15 20:19:32
【问题描述】:

我一直在浏览以前的 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 让我的生活更轻松

【问题讨论】:

标签: python python-3.x pickle


【解决方案1】:

你抛弃自我的方法。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

【讨论】:

  • 当我试图从加载的类中打印变量的值时,这给了我同样的错误:AttributeError: type object 'Char' has no attribute 'lvl'
  • 您能否提供一个可验证的回溯错误示例?因为我无法使用我的代码获得相同的属性错误。
  • 一些帮助我弄清楚问题是什么以及如何解决它的事情。 (1) 我没有意识到我应该将 load() 变成一个变量并将它放在我想要加载的之前 (2) 我还意识到,在我的特定情况下,我需要一个全局变量 (3) [这只是由于我的疏忽,因为我是初学者] 我正在操纵一个论点,而我本应该做另一个论点。我想这不是很清楚,但我希望这篇文章尽可能有帮助。当我有更深入的了解时,我会回来更好地澄清
猜你喜欢
  • 1970-01-01
  • 2021-12-18
  • 2014-03-09
  • 2019-01-20
  • 1970-01-01
  • 2017-10-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多