为什么Pickle不能序列化我的类数组? [英] Why is Pickle not serializing my array of classes?

查看:88
本文介绍了为什么Pickle不能序列化我的类数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用python的pickle将大量自定义类序列化到磁盘.但是,这些类未正确序列化.

I'm trying to serialize a large number of custom classes to disk using python's pickle. However, the classes aren't serializing properly.

看过 docs 是我的理解,我正在尝试做应该工作,但这可能不只是因为我对某事不了解.

Having looked at the docs it's my understanding what I'm trying to do ought to work, but perhaps it's not simply because I'm not understanding something.

我的类在模块的顶层定义.尝试腌制时不会触发任何PicklingError异常.

My classes are defined at the top-level of the module. And no PicklingError exception is being fired when trying to pickle.

这是我的示例代码.取消注释Save()以进行序列化;取消注释Load()即可加载.加载时,不会填充Term的同义词数组,但是会反序列化Term的主要对象.您可以通过检查从Load()函数返回的"loadedTerms"对象来查看此信息.

Here is my sample code. Uncomment Save() to serialize; uncomment Load() to load. When loading, the Synonyms array of Term isn't being populated, but the Main object of Term is being deserialized. You can see this by inspecting the "loadedTerms" object being returned from the Load() function.

我做错了什么?谢谢.

What am I doing wrong? Thanks.

import pickle

class Entry:
    Text = ""

    def __init__(self, text):
       self.Text = text

class Term:

    Main = None
    Synonyms = []


def Save():
    term = Term()
    term.Main = Entry("Dog")
    term.Synonyms.append(Entry("Canine"))
    term.Synonyms.append(Entry("Pursue"))
    term.Synonyms.append(Entry("Follow"))
    term.Synonyms.append(Entry("Plague"))

    terms = []
    terms.append(term)

    with open('output.pickle', 'wb') as p:
        pickle.dump(terms, p)

def Load():
    loadedTerms = []

    with open('output.pickle', 'rb') as p:
        loadedTerms = pickle.load(p)

    return loadedTerms


#Save()
#terms = Load()

推荐答案

Pickle仅保存类的实例属性,但是Synonyms是在类级别定义的列表.您应该使用__init__方法创建列表:

Pickle only saves the instance attributes of a class, but Synonyms is a list, defined at class level. You should create the list in a __init__-method:

import pickle

class Entry:
    def __init__(self, text):
       self.Text = text

class Term:
    def __init__(self):
        self.Main = None
        self.Synonyms = []

def Save():
    term = Term()
    term.Main = Entry("Dog")
    term.Synonyms.append(Entry("Canine"))
    term.Synonyms.append(Entry("Pursue"))
    term.Synonyms.append(Entry("Follow"))
    term.Synonyms.append(Entry("Plague"))

    terms = []
    terms.append(term)

    with open('output.pickle', 'wb') as p:
        pickle.dump(terms, p)

def Load():
    with open('output.pickle', 'rb') as p:
        loadedTerms = pickle.load(p)
    return loadedTerms

这篇关于为什么Pickle不能序列化我的类数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆