Hello Python pickle

思路

  • pickle 是什么html

  • Hello pickle!python

  • pickle 能解析什么?工具

  • 自定义的类怎么使用 pickleui

pickle

pickle 是 Python 里的序列化工具。spa

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.rest

Hello pickle

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

pickle 能解析什么

  • string ?code

  • simple dict ?htm

  • datetime ?get

>>> 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?string

写一个 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."
相关文章
相关标签/搜索