Save a class into a binary file - Python

后端 未结 2 501
萌比男神i
萌比男神i 2020-12-31 22:45

I\'m aware that saving a class into a binary file in c++ is possible using:

file.write(Class_variable, size_of_class, amount_of_saves, file_where_to_save)


        
相关标签:
2条回答
  • 2020-12-31 22:56

    pickle is what you need. The pickle module implements a fundamental, but powerful algorithm for serializing and de-serializing a Python object structure. This is an example

    import pickle
    
    class MyClass:
        def __init__(self,name):
            self.name = name
        def display(self):
            print(self.name)
    
    my = MyClass("someone")
    pickle.dump(my, open("myobject", "wb"))
    me = pickle.load(open("myobject", "rb"))
    me.display()
    
    0 讨论(0)
  • 2020-12-31 22:59

    You can get at the bytes of Python objects to save & restore them like that, but it's not easy to do directly. However, the standard pickle module simplifies the process enormously.

    0 讨论(0)
提交回复
热议问题