如何在Python中完全保存/读取类

发布于 2024-08-23 07:11:12 字数 348 浏览 8 评论 0原文

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()

什么是最简单的方法来做到这一点?

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()

or

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

what is easiest way to do this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

岁月静好 2024-08-30 07:11:12

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

import pickle

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

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

另一种选择是旧模块 marshal

You can (de)serialize with pickle. It is backward-compatible, i.e. it will support all old protocols in future versions.

import pickle

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

But mind that if you transfer pickled objects to another computer, make sure the connection cannot be tampered with as pickle might be unsecure (this is an article that every pickle user should know).

Another alternative is the older module marshal.

把人绕傻吧 2024-08-30 07:11:12

我使用此代码:

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 -类/

I use this code:

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)

This code saves and loads the class from its actual class instance name. Code is from my blog http://www.schurpf.com/python-save-a-class/.

只涨不跌 2024-08-30 07:11:12

看一下 Python 的 pickle 库。

Take a look at Python's pickle library.

水晶透心 2024-08-30 07:11:12

以这种方式使用 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

Use pickle in this way:

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文