Why is Pickle not serializing my array of classes?

前端 未结 1 618
陌清茗
陌清茗 2021-01-28 11:52

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

Having looked at the docs i

相关标签:
1条回答
  • 2021-01-28 12:42

    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
    
    0 讨论(0)
提交回复
热议问题