我正在学习如何使用泡菜。我创建了一个 namedtuple 对象,将其附加到一个列表中,并尝试腌制该列表。但是,我收到以下错误:
pickle.PicklingError: Can't pickle <class '__main__.P'>: it's not found as __main__.P
我发现如果我运行代码而不将其包装在函数中,它会完美运行。包装在函数中时是否需要额外的步骤来腌制对象?
这是我的代码:
from collections import namedtuple
import pickle
def pickle_test():
P = namedtuple("P", "one two three four")
my_list = []
abe = P("abraham", "lincoln", "vampire", "hunter")
my_list.append(abe)
with open('abe.pickle', 'wb') as f:
pickle.dump(abe, f)
pickle_test()