简体   繁体   English

Pickle Load Custom Object 参数未对齐

[英]Pickle Load Custom Object Parameters Misaligned

Car.py:汽车.py:

   class Car(object):
        def __init__(self, year=2023, speed=50):
            self.year = year 
            self.speed = speed
            self.word_index = {}

Util.py:工具.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.加载文件后,整个 Car object 被赋值给 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?所以我最终得到:c2.year:序列化的汽车 object。c2.speed:默认速度为 50 而不是 40。我错过了什么?

You're passing the output of pickle.load as the first arg (ie year ) to Car 's init method.您将 pickle.load 的pickle.load作为第一个参数(即year )传递给Car的 init 方法。 You don't need to pass the output of loading your pickle file to Car 's constructor.您不需要将加载 pickle 文件的 output 传递给Car的构造函数。 Just use pickle.load .只需使用pickle.load

with open('car.pkl', 'rb') as f:
    c2 = pickle.load(f)

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

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