gpt4 book ai didi

python - 在类里面调用时出现 pickle 错误

转载 作者:行者123 更新时间:2023-11-28 21:59:11 24 4
gpt4 key购买 nike

我正在尝试在我的一个类中放置一个方法,该方法允许我对文件进行 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com