22
som = SOM_CLASS() # includes many big difficult data structures
som.hard_work()
som.save_to_disk(filename)
#then later or another program
som = SOM_CLASS()
som.read_from_file(filename)
som.do_anythink_else()

或者

som = SOM_CLASS()
save(som)
#...
load(som)
som.work()

最简单的方法是什么?

4

4 回答 4

26

您可以使用pickle(反)序列化。它是向后兼容的,即它将支持未来版本中的所有旧协议。

import pickle

som = SOM_CLASS()
fileObject = <any file-like object>
pickle.dump(som, fileObject)
#...
som = pickle.load(fileObject)
som.work()

但是请注意,如果您将腌制对象传输到另一台计算机,请确保连接不会被篡改,因为腌制可能不安全(这是每个腌制用户都应该知道的文章)。

另一种选择是较旧的模块marshal

于 2010-02-26T22:12:51.753 回答
11

我使用这段代码:

import cPickle
import traceback

class someClass():
    def __init__(self):
        #set name from variable name. http://stackoverflow.com/questions/1690400/getting-an-instance-name-inside-class-init
        (filename,line_number,function_name,text)=traceback.extract_stack()[-2]
        def_name = text[:text.find('=')].strip()
        self.name = def_name

        try:
            self.load()
        except:
            ##############
            #to demonstrate
            self.someAttribute = 'bla'
            self.someAttribute2 = ['more']
            ##############

            self.save()

    def save(self):
        """save class as self.name.txt"""
        file = open(self.name+'.txt','w')
        file.write(cPickle.dumps(self.__dict__))
        file.close()

    def load(self):
        """try load self.name.txt"""
        file = open(self.name+'.txt','r')
        dataPickle = file.read()
        file.close()

        self.__dict__ = cPickle.loads(dataPickle)

此代码从其实际类实例名称保存和加载类。代码来自我的博客http://www.schurpf.com/python-save-a-class/

于 2012-02-08T21:29:30.380 回答
2

看看 Python 的pickle库。

于 2010-02-26T22:05:52.507 回答
1

pickle以这种方式使用:

import pickle
class Student:
    def __init__(self, name, age, grade):
        self.name = name
        self.age = age
        self.grade = grade # 0 - 100
    def get_grade(self):
        print (self.grade)
s1 = Student("Tim", 19, 95)

#save it
with open(f'test.pickle', 'wb') as file:
    pickle.dump(s1, file) 

#load it
with open(f'test.pickle', 'rb') as file2:
    s1_new = pickle.load(file2)

#check it
s1_new.get_grade()
# it prints 95
于 2021-02-24T17:41:50.457 回答