search

Home  >  Q&A  >  body text

How to use pickle to save instances of classes in Python?

I am a novice, and I am here to ask the experts for advice. . . To save an instance of a class in pickle, do you use pickle.dump() to save the instantiated class into a pkl file after instantiating the class?
For example:
class zxc():

x=1

b=zxc()
with open("zxc.pkl", "wb") as f:

pickle.dump(b, f)

If this is the case, if you need to call this instantiated class to others, should you give the entire class to others? Or can I just give the file?

阿神阿神2792 days ago1149

reply all(2)I'll reply

  • 迷茫

    迷茫2017-06-12 09:29:34

    pickle.load Read the English documentation of this API in detail

    And pickle the entire module’s documentation

    Then the problem can be solved

    reply
    0
  • 淡淡烟草味

    淡淡烟草味2017-06-12 09:29:34

    When pickle.load is executed, Python will try to import the module file containing class zxc. If it cannot be imported, an exception will be thrown. A similar error will occur if the class and module are renamed or the module is moved to another directory.

    So, not only do you need to give the relevant module files to others, but you also need to ensure the consistency of the relative directories.

    reply
    0
  • Cancelreply