Python pickle 如何保存对象?

How does Python pickle save objects?

我想知道是否可以将具有多个 values/properties 的对象保存到一个 pickle 文件中,还是必须单独保存每个值?这是我现在的代码:

def __init__(self, id, targets, binaries):
    self.id = id
    self.targets = targets
    self.binaries = binaries

with open('PI0_Electron_data.pickle', 'wb') as output:
    pickle.dump(PiElectron, output)

为了更好地理解 id 是一个整数,目标和二进制文件都是 numpy 数组。我能否从这个单个 pickle 文件中获取对象的 ID、目标和二进制文件,还是必须创建三个 pickle 文件?另外,我将如何从 pickle 文件中提取数据?

您的代码应如下所示:

>>> class Thing(object):
...   def __init__(self, id, targets, binaries):
...     self.id = id
...     self.targets = targets
...     self.binaries = binaries
... 
>>> import numpy as np
>>> t = Thing(1, np.arange(3), np.arange(3,9,2))
>>> 
>>> import dill
>>> with open('electron_data.pkl', 'w') as f:
...   dill.dump(t, f)
... 
>>>

我使用 dill 来为您提供更好的序列化……本质上,dill 可以轻松地 pickle class 个实例——以及大多数 python 个对象。然后,当您想要取回对象时,您需要 load.

Python 2.7.10 (default, May 25 2015, 13:16:30) 
[GCC 4.2.1 Compatible Apple LLVM 5.1 (clang-503.0.40)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import dill
>>> with open('electron_data.pkl', 'r') as f:
...   t = dill.load(f)
... 
>>> t
<__main__.Thing object at 0x100394410>
>>> t.id
1
>>> t.targets
array([0, 1, 2])
>>> t.binaries
array([3, 5, 7])
>>>
>>> print dill.source.getsource(t.__class__)
class Thing(object):
  def __init__(self, id, targets, binaries):
    self.id = id
    self.targets = targets
    self.binaries = binaries

>>> 

我希望这有助于回答您的问题……如果您的实际代码更复杂(我假设是这样),它应该仍然可以工作,除非有一个不可 picklable 的对象。