if __name__ == "__main__":
h1 = Person(5)
print (h1)
如上所示,我有一个类h1
的对象Person
需要保存为文本文件(.txt)。我想知道如何实现这种持久性并将其读回来?
有些用户建议使用泡菜,我想我可能需要更多细节。
答案 0 :(得分:1)
这是一个可以帮助您入门的解决方案。我重命名了人员实例名称并将参数更改为名称; - )
#! /usr/bin/env python
"""Note: Documentation clearly states, that classes can be pickled,
but only iff they "are defined at the top level of a module"."""
from __future__ import print_function
import pickle
class Person(object):
"""Minimal class to showcase (un)pickle."""
FULL_NAME_DEFAULT = 'N.N.'
def __init__(self, full_name=None):
"""Detected initializer (show unpickling behaviour)."""
if full_name is not None:
self.full_name = full_name
else:
self.full_name = self.FULL_NAME_DEFAULT
print("Initializer called!")
self.say_hello()
def say_hello(self):
"""A method to say a personalized hello."""
print("Hello! My name is '%s'" % (self.full_name,))
def main():
"""Drive the dumps and loads of Person instances."""
number_one = Person("Jane Awsome")
print(number_one)
print("# Serialize the person number_one ... with default protocol:")
serialized_person = pickle.dumps(number_one)
print("# Dump of the data representing the serialized_person:")
print(serialized_person)
print("# Now for something completely different ...")
reborn = pickle.loads(serialized_person)
print("# Back again a copy of number_one, no __init__ called ;-)")
reborn.say_hello()
if __name__ == "__main__":
main()
在我的机器上运行并使用python v2时,会导致:
Initializer called!
Hello! My name is 'Jane Awsome'
<__main__.Person object at 0x102e730d0>
# Serialize the person number_one ... with default protocol:
# Dump of the data representing the serialized_person:
ccopy_reg
_reconstructor
p0
(c__main__
Person
p1
c__builtin__
object
p2
Ntp3
Rp4
(dp5
S'full_name'
p6
S'Jane Awsome'
p7
sb.
# Now for something completely different ...
# Back again a copy of number_one, no __init__ called ;-)
Hello! My name is 'Jane Awsome'
使用Python v3执行:
Initializer called!
Hello! My name is 'Jane Awsome'
<__main__.Person object at 0x1010c8780>
# Serialize the person number_one ... with default protocol:
# Dump of the data representing the serialized_person:
b'\x80\x03c__main__\nPerson\nq\x00)\x81q\x01}q\x02X\t\x00\x00\x00full_nameq\x03X\x0b\x00\x00\x00Jane Awsomeq\x04sb.'
# Now for something completely different ...
# Back again a copy of number_one, no __init__ called ;-)
Hello! My name is 'Jane Awsome'
默认协议已经改变了我想: - )
请尝试在规范性文档中查找扩展和拟合用例所需的详细信息,例如: 12.1. pickle — Python object serialization
...并且在打开时,如果数据可能已被调整,请务必小心,因为您必须依赖于您对通过此渠道的信任。它是一个强大的。
与JSON和其他(de)序列化模块一样,有针对字符串,文件等优化的方法。您可以在文档中轻松阅读。这里我使用dumps()和loads(),其中后缀s代表字符串。
将序列化人员的内容(此处为字符串变量)输出到文件并在xou中读回可以很容易地在前面提到的优秀Python文档中查找。