简体   繁体   English

如何使用Pickle加载类实例(初学者支持到pickle jar中)

[英]How to load a class instance with Pickle (beginner backed into a pickle jar)

I have been going through previous SO answers and have yet to find an answer. 我已经经历过以前的SO答案,但尚未找到答案。 I am trying to save and load a class instance with pickle and I keep getting the error: type object 'Foo' has no attribute 'bar'. 我正在尝试使用pickle保存和加载类实例,并且不断收到错误消息:类型对象'Foo'没有属性'bar'。 my code is below: 我的代码如下:

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)

So my main issue is that when I try to load the game, it tells me: AttributeError: type object 'Char' has no attribute 'lvl' 所以我的主要问题是,当我尝试加载游戏时,它告诉我:AttributeError:类型对象'Char'没有属性'lvl'

While I cannot understand the pk1 file, It is being updated with each save, so I know that the save functionality is working properly.. I am just not sure how to take the information in the pk1 file and replace it with Char. 虽然我听不懂pk1文件,但是每次保存时都会对其进行更新,因此我知道保存功能可以正常工作。.我只是不确定如何获取pk1文件中的信息并将其替换为Char。 init 在里面

I am thinking about just switching to JSON because I have it implemented in other parts of my code.. but I would like to make my life easier by using pickle in this case 我正在考虑只切换到JSON,因为我已经在代码的其他部分中实现了它。.但是在这种情况下,我想通过使用pickle来简化生活

Your approach of dumping self. 您抛弃自我的方法。 dict looks a bit convoluted to me. dict对我来说似乎有点令人费解。 The common way to dump an instance of your class Char would be as follows: 转储类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)

For sake of clearness, I will add the usage of the above class and method. 为了清楚起见,我将添加上述类和方法的用法。

$ python -i 53796917.py
>>> c=Char()
>>> c.lvl = 10
>>> c.save()
>>>
$ python -i 53796917.py
>>> c=load()
>>> c.lvl
10

Doesn't throws any AttributeError 不抛出任何AttributeError

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM