向现有类添加函数的最简单方法 [英] Easiest way to add a function to existing class
问题描述
我正在使用python的内置扩展模块来管理一些简单的字典.我遇到的问题是我想使用with shelve.open(filename) as f:
,但是当我尝试使用它时,它声称DbfilenameShelf没有属性__exit__
.
I'm using the python's built-in shelve module to manage some simple dictionaries. The problem I'm having is I want to use with shelve.open(filename) as f:
, but when I try it claims DbfilenameShelf has no attribute __exit__
.
因此,我猜想最简单的方法是将其包装在另一个类中,并在该包装器中添加一个__exit__
函数.我试过了:
So, I'm guessing the easiest way to do this is to wrap it in another class and add an __exit__
function to that wrapper. I tried this:
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)
它告诉我给它一个无效的参数.
But when I tried to instantiate the wrapper like so: wrapped = Wrapper(filename)
it tells me I'm giving it an invalid argument.
要求的错误:
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
的工具:
Don't subclass it. Python comes with a tool for automatically calling close()
, contextlib.closing
:
from contextlib import closing
with closing(shelve.open(filename)) as f:
# your 'with' block here
将在with
块末尾自动调用shelve.open(filename)
返回的对象的close()
方法.
will automatically call the close()
method of the object returned by shelve.open(filename)
at the end of the with
block.
这篇关于向现有类添加函数的最简单方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!