我让我上课,就是把自己当作一个泡菜。
我希望该课程能够从泡菜中导入数据......:
喜欢:
myFirstInstance.printV1() #variable is set to 4 by the __init__
myFirstInstance.write2Pickle(myPickleFile.pkl)
mySecondInstance.loadPickleData(myPickleFile.pkl)
mySecondInstance.printV1() # should give 4 back from the firstInstance...
答案 0 :(得分:2)
使用pickle
非常简单:
import cPickle as pickle
with open('a.pkl', 'wb') as f:
pickle.dump(obj, f)
with open('a.pkl', 'rb') as f:
obj = pickle.load(f)
如果您的课程需要特殊的逻辑来进行腌制/取消篡改,您应该覆盖pickle protocol使用的方法(例如__getstate__
/ __setstate__
)。这样,上面的用法仍然有效。
答案 1 :(得分:0)
这有点棘手,因为您正在从现有实例中更改类实例的状态...而且您还希望从类的实例中挑选类的实例。为了简化类实例的修补,我使用dill
代替pickle
。
>>> import dill
>>>
>>> class MyClass(object):
... def __init__(self, x):
... self.V1 = x
... def printV1(self):
... print(self.V1)
... def write2Pickle(self, filename):
... with open(filename, 'wb') as f:
... dill.dump(self, f)
... def loadPickleData(self, filename):
... with open(filename, 'rb') as f:
... obj = dill.load(f)
... self.V1 = obj.V1
... # similarly for other instance state variables
...
>>> myFirstInstance = MyClass(4)
>>> myFirstInstance.printV1()
4
>>> myFirstInstance.write2Pickle('myPickleFile.pkl')
>>> del myFirstInstance
>>> mySecondInstance = MyClass(1)
>>> mySecondInstance.printV1()
1
>>> mySecondInstance.loadPickleData('myPickleFile.pkl')
>>> mySecondInstance.printV1()
4
我注意到,不要将酸洗和取消作为一种类方法进行编程练习可能更好...除非有真的它应该存在的理由
。此外,您可以直接取消拼写并获得一个非常好的新实例,因此除非您需要覆盖现有实例的状态,否则无需将取消作为类方法。
>>> with open('myPickleFile.pkl', 'rb') as f:
... myThirdInstance = dill.load(f)
...
>>> myThirdInstance.printV1()
4
同样,您可以在实例外部使用dump
,它也可以创建一个新的pickle实例。