我尝试在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课程,其中讲师使用了第一个版本,没有任何问题。在
您需要了解
with
的用途。它基本上用于自动处理调用它的对象的设置和清理,前提是这些对象支持使用这样的设置和清理函数。特别是,setup的对象是__enter__
函数,而teardown的等效对象是__exit__
函数。下面是一个例子:现在,用
^{pr2}$with...as
实例化一个Foo
的对象:如您所见,
with...as
将强制调用这些setup/teardown方法,如果它们丢失,则会引发一个AttributeError
,因为试图调用一个不存在的实例方法。在这与您的
shelve
对象是一样的-它没有在其类中定义__exit__
方法,因此使用with
将不起作用。在根据documentation,对上下文管理器的支持是从3.4版及以后的版本中添加的。如果上下文管理器不工作,那就意味着你的版本比较旧。在
相关问题 更多 >
编程相关推荐