我正在使用 python 的内置搁置模块来管理一些简单的词典。我遇到的问题是我想使用 with shelve.open(filename) as f:
,但是当我尝试时它声称 DbfilenameShelf 没有属性 __exit__
。
所以,我猜最简单的方法是将它包装在另一个类中,并向该包装器添加一个 __exit__
函数。我试过这个:
class Wrapper(shelve.DbfilenameShelf):
def __exit__(self):
self.close()
def __init__(self, filename, writeback=False):
shelve.DbfilenameShelf.__init__(self, filename, flag='c', protocol=None, writeback=False)
但是当我尝试像这样实例化包装器时:wrapped = Wrapper(filename)
它告诉我我正在给它一个无效参数。
请求的错误:
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "<input>", line 5, in __init__
File "C:\Python27\Lib\shelve.py", line 223, in __init__
Shelf.__init__(self, anydbm.open(filename, flag), protocol, writeback)
File "C:\Python27\Lib\anydbm.py", line 85, in open
return mod.open(file, flag, mode)
File "C:\Python27\Lib\dbhash.py", line 18, in open
return bsddb.hashopen(file, flag, mode)
File "C:\Python27\Lib\bsddb\__init__.py", line 364, in hashopen
d.open(file, db.DB_HASH, flags, mode)
DBInvalidArgError: (22, 'Invalid argument')
最佳答案
不要子类化它。 Python自带自动调用close()
的工具,contextlib.closing
:
from contextlib import closing
with closing(shelve.open(filename)) as f:
# your 'with' block here
会在with
block 的末尾自动调用shelve.open(filename)
返回的对象的close()
方法.
关于python - 向现有类添加功能的最简单方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7489732/