腌制类变量和实例变量? [英] Pickle both class variables and instance variables?
本文介绍了腌制类变量和实例变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
斑点文档指出:当类实例被腌制时,其类的数据不会与它们一起被腌制.只有实例数据才被腌制."谁能提供在腌制和解腌时包括类变量和实例变量的配方?
The pickle documentation states that "when class instances are pickled, their class’s data are not pickled along with them. Only the instance data are pickled." Can anyone provide a recipe for including class variables as well as instance variables when pickling and unpickling?
推荐答案
使用dill
代替泡菜,并精确地编码您可能已经做过的事情.
Use dill
instead of pickle, and code exactly how you probably have done already.
>>> class A(object):
... y = 1
... x = 0
... def __call__(self, x):
... self.x = x
... return self.x + self.y
...
>>> b = A()
>>> b.y = 4
>>> b(2)
6
>>> b.z = 5
>>> import dill
>>> _b = dill.dumps(b)
>>> b_ = dill.loads(_b)
>>>
>>> b_.z
5
>>> b_.x
2
>>> b_.y
4
>>>
>>> A.y = 100
>>> c = A()
>>> _c = dill.dumps(c)
>>> c_ = dill.loads(_c)
>>> c_.y
100
这篇关于腌制类变量和实例变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文