我正在尝试在我的一个类中放置一个方法,该方法允许我对文件进行 pickle 和 unpickle。例如,我有
import pickle
class SomeClass:
def otherMethods:
pass
def save_to_file(self, filename, file_to_save):
with (filename,'wb') as output:
pickle.dump(file_to_save,output,pickle.HIGHEST_PROTOCOL)
print("Data has been saved.")
现在,当我创建这个“SomeClass”的实例时,我希望能够从终端如下调用...
myfile = [1,2,3] # or anything else
SomeClass.save_to_file('myfile.pk',myfile)
但是,抛出的是:
'AttributeError: __exit__'
我看到过一些不同的帖子,人们在类似用例方面遇到困难,但我一直无法弄清楚它们如何适用于我的情况。非常感谢您的帮助。
最佳答案
open
丢失:
with open(filename,'wb') as output:
with 语句需要一个带有 __enter__
和 __exit__
方法的上下文管理器,并引发 AttributeError
因为元组 (filename,' wb')
没有它们。
关于python - 在类里面调用时出现 pickle 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16976724/