python中pickle模块无法导入_Python:使用pickle模块保存和加载对象时出错

I am trying to load and save objects with this piece of code I get it from a question I asked a week ago: Python: saving and loading objects and using pickle.

The piece of code is this:

class Fruits: pass

banana = Fruits()

banana.color = 'yellow'

banana.value = 30

import pickle

filehandler = open("Fruits.obj","wb")

pickle.dump(banana,filehandler)

filehandler.close()

file = open("Fruits.obj",'rb')

object_file = pickle.load(file)

file.close()

print(object_file.color, object_file.value, sep=', ')

At a first glance the piece of code works well, getting load and see the 'color' and 'value' of the saved object.

But, what I pursuit is to close a session, open a new one and load what I save in a past session. I close the session after putting the line filehandler.close() and I open a new one and I put the rest of your code, then after putting object_file = pickle.load(file) I get this error:

Traceback (most recent call last):

File "", line 1, in

object_file = pickle.load(file)

File "C:\Python31\lib\pickle.py", line 1365, in load

encoding=encoding, errors=errors).load()

AttributeError: 'module' object has no attribute 'Fruits'

Can anyone explain me what this error message means and telling me how to solve this problem?

Thank so much and happy new year!!

解决方案

Python does not pickle whole classes. Only the names. Therefore you must have the module that contains them saved to a file and importable at the time they are unpickled. Python will then re-import them.

If you run into problems, you may need to define special helper methods, __getstate__ and __setstate__ that are used for pickling.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值