Pickle Load Custom Object Parameters Misaligned
Question:
Car.py:
class Car(object):
def __init__(self, year=2023, speed=50):
self.year = year
self.speed = speed
self.word_index = {}
Util.py:
from custom.Car import Car
c1 = Car(2020, 40)
picklefile = open('car.pkl', 'wb')
pickle.dump(c1, picklefile)
with open('car.pkl', 'rb') as f:
c2 = Car(pickle.load(f))
After loading the file, the entire Car object is assigned to self.year. So I end up have:
c2.year: The serialized Car object.
c2.speed: default speed of 50 instead of 40.
What am I missing?
Answers:
You’re passing the output of pickle.load
as the first arg (i.e. year
) to Car
‘s init method. You don’t need to pass the output of loading your pickle file to Car
‘s constructor. Just use pickle.load
.
with open('car.pkl', 'rb') as f:
c2 = pickle.load(f)
Car.py:
class Car(object):
def __init__(self, year=2023, speed=50):
self.year = year
self.speed = speed
self.word_index = {}
Util.py:
from custom.Car import Car
c1 = Car(2020, 40)
picklefile = open('car.pkl', 'wb')
pickle.dump(c1, picklefile)
with open('car.pkl', 'rb') as f:
c2 = Car(pickle.load(f))
After loading the file, the entire Car object is assigned to self.year. So I end up have:
c2.year: The serialized Car object.
c2.speed: default speed of 50 instead of 40.
What am I missing?
You’re passing the output of pickle.load
as the first arg (i.e. year
) to Car
‘s init method. You don’t need to pass the output of loading your pickle file to Car
‘s constructor. Just use pickle.load
.
with open('car.pkl', 'rb') as f:
c2 = pickle.load(f)