How to use pickle to save instances of classes in Python?
阿神
阿神 2017-06-12 09:27:34
0
2
1007

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?

阿神
阿神

闭关修行中......

reply all (2)
迷茫

pickle.loadRead the English documentation of this API in detail

And pickle the entire module’s documentation

Then the problem can be solved

    淡淡烟草味

    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.

      Latest Downloads
      More>
      Web Effects
      Website Source Code
      Website Materials
      Front End Template
      About us Disclaimer Sitemap
      php.cn:Public welfare online PHP training,Help PHP learners grow quickly!