gnr*_*gnr 3 python identity pickle python-3.x
有没有办法保留腌制对象的身份,即具有以下打印True:
import pickle
class Foo:
pass
x = Foo()
print(x is pickle.loads(pickle.dumps(x))) #False
Run Code Online (Sandbox Code Playgroud)
我在Linux机器上使用cPickle和cpython 3.x,不需要可移植的东西.
对的,这是可能的; 你需要在腌制结果中加入"身份"一些方法; 在这种情况下,最自然的使用方法__getnewargs__和__new__方法返回现有的缓存实例.
import uuid
import weakref
class Foo(object):
ident_cache = weakref.WeakValueDictionary()
def __new__(cls, identity=None, **kwargs):
if identity is None:
identity = uuid.uuid1()
try:
self = cls.ident_cache[identity]
except KeyError:
self = super(Foo, cls).__new__(cls)
self.__identity = identity
self.__init__(**kwargs)
cls.ident_cache[identity] = self
return self
def __getnewargs__(self):
return (self.__identity,)
def __init__(self, foo):
self.foo = foo
Run Code Online (Sandbox Code Playgroud)
>>> import pickle
>>> a = Foo(foo=1)
>>> b = pickle.loads(pickle.dumps(a, pickle.HIGHEST_PROTOCOL))
>>> a is b
True
Run Code Online (Sandbox Code Playgroud)
重要的一点是你必须使用协议版本2(或更高,假设); 因为否则,__new__永远不会被召唤.这只是一个问题pickle.dumps,loads不在乎.
| 归档时间: |
|
| 查看次数: |
439 次 |
| 最近记录: |