Pickle both class variables and instance variables

2019-02-27 01:51发布

问题:

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?

回答1:

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


标签: python pickle