在课堂上调用时发生错误

Fla*_*tor 2 python pickle

我正在尝试在我的一个类中放置一个方法,这将允许我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.")
Run Code Online (Sandbox Code Playgroud)

现在,当我创建这个'SomeClass'的实例时,我希望能够从终端调用如下...

myfile = [1,2,3] # or anything else
SomeClass.save_to_file('myfile.pk',myfile)
Run Code Online (Sandbox Code Playgroud)

然而,被抛出的是:

'AttributeError: __exit__'
Run Code Online (Sandbox Code Playgroud)

我看过一些人在使用类似用例时遇到困难的帖子,但是我无法弄清楚它们在我的情况下是如何应用的.非常感谢帮助.

Jan*_*ila 5

open 不见了:

with open(filename,'wb') as output:
Run Code Online (Sandbox Code Playgroud)

with语句需要一个带有__enter____exit__方法的上下文管理器,并且AttributeError因为元组(filename,'wb')没有它们而引发.