python - 向现有类添加功能的最简单方法

标签 python wrapper shelve

我正在使用 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/

相关文章:

python - 搁置代码给出 KeyError

python - 并行更新python中的搁置字典

Python 扭曲 : Preventing buffering between tcp reader and web resource

python - 在 Python 中从字符串中删除元音的正确代码

python - 如何在 Python 中创建漂亮的 shell 命令包装器

python - 我的 python api 包装类中的字符串错误

Python Shelf 能够创建但无法打开 Shelf

python - 如何在ansible中设置多个ansible_python_interpreter变量

python - 如何根据时间和日期输入进行过滤和分类

c++ - 包装 C# C++