【问题标题】:How to pickle class attributes?如何腌制类属性?
【发布时间】:2021-08-06 22:12:37
【问题描述】:
import pickle
import os

class Animal:
    records = dict()    
    def __init__(self, name):
        self.name = name

while True:
    answer = input("-->")
    
    if answer == "add":
        name = input("name : ")
        
        new_animal = Animal(name)
        Animal.records[name] = new_animal

        with open("data.p", "wb") as f:
            pickle.dump(Animal.records, f)

    elif answer == "show":
        with open("data.p", "rb") as f:
            print(pickle.load(f))

我用pickle 模块保存了records。重新启动程序后,如果我查询records的内容而不添加新数据,我可以看到记录,但是如果我添加新数据,我就看不到旧记录。为什么我看不到旧记录?

【问题讨论】:

标签: python class oop pickle


【解决方案1】:

您只需更改代码的 else 部分即可使其正常工作。

  elif answer == "show":
        with open("data.p", "rb") as f:
            Animal.records = pickle.load(f) #reload your object
            print(Animal.records)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-27
    • 2022-06-26
    • 2011-06-08
    • 1970-01-01
    • 2014-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多