shelve模块不能与“with”statement一起使用

2024-04-19 13:28:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试在python中使用shelve模块,并尝试将其与“with”语句结合使用,但在尝试使用时,出现以下错误:

with shelve.open('shelve', 'c') as shlv_file:
    shlv_file['title']    = 'The main title of my app'
    shlv_file['datatype'] = 'data type int32'
    shlv_file['content']  = 'Lorem ipsum'
    shlv_file['refs']     = '<htppsa: asda.com>'

print(shlv_file)

引发以下错误:

^{pr2}$

虽然这样做:

shlv_file = shelve.open('data/shelve', 'c')
shlv_file['title']    = 'The main title of my app'
shlv_file['datatype'] = 'data type int32'
shlv_file['content']  = 'Lorem ipsum'
shlv_file['refs']     = '<htppsa: asda.com>'
shlv_file.close()

shlv_file = shelve.open('data/shelve', 'c')
shlv_file['new_filed'] = 'bla bla bla'
print(shlv_file)

不会引发错误,并且输出是预期的输出。第一个语法有什么问题?我在看一个python课程,其中讲师使用了第一个版本,没有任何问题。在


Tags: oftheappdatatitlemainmy错误
1条回答
网友
1楼 · 发布于 2024-04-19 13:28:53

您需要了解with的用途。它基本上用于自动处理调用它的对象的设置和清理,前提是这些对象支持使用这样的设置和清理函数。特别是,setup的对象是__enter__函数,而teardown的等效对象是__exit__函数。下面是一个例子:

In [355]: class Foo():
     ...:     def __enter__(self):
     ...:         print("Start!")
     ...:         return self
     ...:     def __exit__(self, type, value, traceback):
     ...:         print("End!")
     ...:         

现在,用with...as实例化一个Foo的对象:

^{pr2}$

如您所见,with...as将强制调用这些setup/teardown方法,如果它们丢失,则会引发一个AttributeError,因为试图调用一个不存在的实例方法。在

这与您的shelve对象是一样的-它没有在其类中定义__exit__方法,因此使用with将不起作用。在


根据documentation,对上下文管理器的支持是从3.4版及以后的版本中添加的。如果上下文管理器不工作,那就意味着你的版本比较旧。在

相关问题 更多 >