Вопрос

When I pickle my game object, It pickles everything except my lists. I check this by checking the lists after I have unpickled it.

Here is my pickle and unpickle code:

    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

How I call pickle_me:

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

How I unpickle:

            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()

Any idea why the lists become empty? This is what I am serialising (the lists are full when I pickle it. Activities is full when I unpickle it, but not the lists).

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}
Это было полезно?

Решение

Initialize the members inside of __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...
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top