如何腌制 class 属性?

How to pickle class attributes?

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的内容,可以看到记录,但是添加新数据,就看不到旧记录了。为什么我看不到旧记录?

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

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