Home > front end >  How to store self values with Pickle?
How to store self values with Pickle?

Time:08-20

class Player:
    def __init__(self):
        self.money = 0
        self.level = 0
        self.xp = 0
        self.xp_until_level = 20
        self.taxi_car = "Cabbie"
        self.busines = "Нет"
        self.busines_income = 1000
        self.upgrade_cost = 10000
        self.car_speed = 10
        self.car_level = 0
        self.drives_until_new_car = 20

p = Player()

I don’t know how to save self values. I making my text game and saving data is my number one problem.

CodePudding user response:

self values are attributes of your instance. Just pickle your insntace (here p) and it stores all the attributes:

import pickle

class Player:
    def __init__(self):
        self.money = 0
        self.level = 0
        self.xp = 0
        self.xp_until_level = 20
        self.taxi_car = "Cabbie"
        self.busines = "Нет"
        self.busines_income = 1000
        self.upgrade_cost = 10000
        self.car_speed = 10
        self.car_level = 0
        self.drives_until_new_car = 20

p = Player()

pickled = pickle.dumps(p)
new_obj = pickle.loads(pickled)
print(new_obj.taxi_car)  # Cabbie

CodePudding user response:

Storing the class instance to a binary file:

The class instance (or any other object) can be stored to, or read from, a pickled (serialised) binary file for later use or archiving.

For example:

import pickle

# Create a class instance (as you have done).    
p = Player()

# Store the class instance to a file.
with open('./cabbie.p', 'wb') as f:  # <-- Note the 'wb' mode, for write-binary
    pickle.dump(p, f)
    
# Read the class instance from a file.
with open('./cabbie.p', 'rb') as f:  # <-- Note the 'rb' mode, for read-binary
    data = pickle.load(f)
    

Testing:

>>> vars(data)

{'money': 0,
 'level': 0,
 'xp': 0,
 'xp_until_level': 20,
 'taxi_car': 'Cabbie',
 'busines': 'Нет',
 'busines_income': 1000,
 'upgrade_cost': 10000,
 'car_speed': 10,
 'car_level': 0,
 'drives_until_new_car': 20}
  • Related