1

思路

  • pickle 是什么

  • Hello pickle!

  • pickle 能解析什么?

  • 自定义的类怎么使用 pickle

pickle

pickle 是 Python 里的序列化工具。

pickle can save and restore class instances transparently, however the class definition must be importable and live in the same module as when the object was stored.

Hello pickle

>>> import pickle
>>> s = 'Hello pickle~'
>>> sp = pickle.dumps(s)
>>> "S'Hello pickle'\np0\n."
>>> sp
>>> pickle.loads(sp)

pickle 能解析什么

  • string ?

  • simple dict ?

  • datetime ?

>>> pickle.loads(pickle.dumps({'a': 'aaa', 'n': 123}))
{'a': 'aaa', 'n': 123}
>>> pickle.dumps(datetime.datetime.now())
"cdatetime\ndatetime\np0\n(S'\\x07\\xe0\\x05\\x1f\\x0e:\\x15\\x03\\x17\\xde'\np1\ntp2\nRp3\n."
>>> pickle.loads("cdatetime\ndatetime\np0\n(S'\\x07\\xe0\\x05\\x1f\\x0e:\\x15\\x03\\x17\\xde'\np1\ntp2\nRp3\n.")
datetime.datetime(2016, 5, 31, 14, 57, 51, 537279)

11.1.4. What can be pickled and unpickled?

写一个 picklable 的类

发现如下的类是可以直接 pickle 的,且 unpickle 的地方只要引用过了 User Class 就可以成功 unpickle。

class User(object):
    def __init__(self, id, name):
        self.id = id
        self.name = name
>>> u1 = User(1, 'a')
>>> pickle.dumps(u1)
"ccopy_reg\n_reconstructor\np0\n(c__main__\nUser\np1\nc__builtin__\nobject\np2\nNtp3\nRp4\n(dp5\nS'id'\np6\nI1\nsS'name'\np7\nS'a'\np8\nsb."

常伟佳
310 声望16 粉丝

« 上一篇
Hello fswatch
下一篇 »
Hello Timezone

引用和评论

0 条评论