如何将 class 个对象腌制到文本文件中并读回?

How to pickle class objects into text file and read it back?

if __name__ == "__main__":  
    h1 = Person(5)
    print (h1)

如上所示,我有一个对象 h1 of class Person 需要保存为文本文件 (.txt)。我想知道如何实现这种坚持并回头阅读?

一些用户建议使用 pickle,我想我可能需要在这里提供更多详细信息。

这是一个可能的解决方案,可以帮助您入门。我重命名了 person 实例名称并将参数更改为名称 ;-)

#! /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

... 并且在 unpickling 时始终小心,如果数据可能已被篡改,因为您必须依靠您的信任通过此渠道进入的内容。这是一个强大的。

与 JSON 和其他(反)序列化模块一样,有针对字符串、文件等优化的方法。您可以在文档中轻松阅读。这里我使用了 dumps() 和 loads() ,其中后缀 s 代表字符串。

要将序列化人员的内容(此处为字符串变量)输出到文件并在 xou 中读回,可以轻松地在上述优秀的 Python 文档中查找。