我试图腌制一个自定义类的实例,这个类有一个名为“widgets”的属性,其中包含一个小部件对象列表。当我腌制容器时,列表丢失了。不能在对象中腌制列表吗?
import pickle
filename = 'container.pkl'
class Container(object):
widgets = []
class Widget(object):
pass
c = Container()
c.name = "My Container"
w = Widget()
w.name = "My Widget"
c.widgets.append(w)
data = open(filename, 'wb')
pickle.dump(c, data)
data.close()
后来我试着解开...
# assume I have imported the classes and filename here
data = open(filename, 'rb')
container = pickle.load(data)
data.close()
print container.name # shows the pickled name
print container.widgets # shows []
我尝试过 pickle 和 cPickle ,结果相同。