pickle 是什麼html
Hello pickle!python
pickle 能解析什麼?工具
自定義的類怎麼使用 pickleui
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
>>> import pickle >>> s = 'Hello pickle~' >>> sp = pickle.dumps(s) >>> "S'Hello pickle'\np0\n." >>> sp >>> pickle.loads(sp)
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
發現以下的類是能夠直接 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."