【问题标题】:Pickle not serialising my lists - PythonPickle 没有序列化我的列表 - Python
【发布时间】:2014-03-12 21:27:55
【问题描述】:

当我腌制我的游戏对象时,它会腌制除我的列表之外的所有内容。在我解开它后,我通过检查列表来检查它。

这是我的pickle和unpickle代码:

    def pickle_me(self, obj):
        import pickle
        output = open('obj_state.pkl', 'wb')
        pickle.dump(obj, output, -1)
        output.close()
        print('pickled')

    def unpickle_me(self):
        import pickle
        pkl_file = open('obj_state.pkl', 'rb')
        the_obj = pickle.load(pkl_file)
        pkl_file.close()
        return the_obj

我怎么称呼pickle_me:

self.features.pickle_me(model.zimp.the_game)

我如何解压:

            model.zimp.the_game = self.features.unpickle_me()
            print('You have loaded the last played game. \n')
            model.zimp.the_game.print_stats()
            model.zimp.the_game.the_user.print_stats()

知道为什么列表会变空吗?这就是我要序列化的内容(我腌制时列表已满。取消腌制时活动已满,但列表未满)。

class Game(object):
    """Template for the Zimp game."""
    the_user = None
    the_time = None
    _indoor_location_cards = []
    _outdoor_location_cards = []
    played_location_cards = []
    played_game_dev_cards = []
    game_dev_cards = []
    items = {}
    activities = {'You taste something icky in your mouth': -1,
        'You slip on nasty goo': -1,
        'The smell of blood is in the air': 0,
        'You pee yourself a little bit': 0,
        'You find a twinkie': 1,
        'A bat poops in your eye': -1,
        'Justin Bieber tries to save you': -1,
        'You spot a zombie eating himself': 0,
        'You hear terrible screams': 0}

【问题讨论】:

    标签: python list pickle


    【解决方案1】:

    初始化__init__内部的成员:

    class Game(object):
        """Template for the Zimp game."""
    
        def __init__(self):
            self.the_user = None
            self.the_time = None
            self._indoor_location_cards = []
            self._outdoor_location_cards = []
            self.played_location_cards = []
            self.played_game_dev_cards = []
            self.game_dev_cards = []
            self.items = {}
            self.activities = {'You taste something icky in your mouth': -1,
                'You slip on nasty goo': -1,
                'The smell of blood is in the air': 0,
                'You pee yourself a little bit': 0,
                'You find a twinkie': 1,
                'A bat poops in your eye': -1,
                'Justin Bieber tries to save you': -1,
                'You spot a zombie eating himself': 0,
                'You hear terrible screams': 0}
    
    Interesting activities...
    

    【讨论】:

      猜你喜欢
      • 2013-01-16
      • 2012-02-16
      • 1970-01-01
      • 2011-03-03
      • 2019-04-09
      • 1970-01-01
      • 1970-01-01
      • 2015-03-11
      相关资源
      最近更新 更多