在Python中将__repr__与shelve模块一起使用

时间

我正在为货架模块编写包装类,并且打算像字典一样使用它。这是代码:

import shelve

class MyShelve:

    def __init__(self, filename='myshelve.db'):
        self.s = shelve.open(filename)

    def __del__(self):
        self.s.close()

    def __repr__(self):
        return repr(self.s)

    def __getitem__(self, k):
        return self.s.get(k, None)

    def __setitem__(self, k, v):
        self.s[k] = v

直到我使用“ dict中的键”一词,一切似乎都可以正常工作。这是一个示例会话:

>>> d = {'1': 'One', '2': 'Two'}
>>> d
{'1': 'One', '2': 'Two'}
>>> '1' in d
True
>>> from myshelve import MyShelve
>>> s = MyShelve()
>>> s['1'] = 'One'
>>> s['2'] = 'Two'
>>> s
{'1': 'One', '2': 'Two'}
>>> '1' in s.s
True
>>> '1' in s
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "myshelve.py", line 15, in __getitem__
    return self.s.get(k, None)
  File "/usr/lib64/python2.7/shelve.py", line 113, in get
    if key in self.dict:
  File "/usr/lib64/python2.7/_abcoll.py", line 369, in __contains__
    self[key]
  File "/usr/lib64/python2.7/bsddb/__init__.py", line 270, in __getitem__
    return _DeadlockWrap(lambda: self.db[key])  # self.db[key]
  File "/usr/lib64/python2.7/bsddb/dbutils.py", line 68, in DeadlockWrap
    return function(*_args, **_kwargs)
  File "/usr/lib64/python2.7/bsddb/__init__.py", line 270, in <lambda>
    return _DeadlockWrap(lambda: self.db[key])  # self.db[key]
TypeError: Integer keys only allowed for Recno and Queue DB's

我究竟做错了什么?

游戏Brainiac

首先,始终要继承自object它将使您免于以后的麻烦。其次,您需要使用__contains__第三,当使用__contains____getitem__任何dunder方法处理此事时,请确保使用异常,即try-except块。这是您要寻找的样本:

class MyShelve(object):

    def __init__(self, filename='myshelve.db'):
        self.s = shelve.open(filename)

    def __del__(self):
        self.s.close()

    def __repr__(self):
        return repr(self.s)

    def __getitem__(self, item):
        return self.s.get(item, False)

    def __contains__(self, item):
        try:
            return item in self.s
        except TypeError:
            return False

    def __setitem__(self, k, v):
        self.s[k] = v

演示:

In[3]: from shelving import MyShelve
In[4]: s = MyShelve()
In[5]: s['1'] = 'One'
In[6]: s['2'] = 'Two'
In[7]: '1' in s
Out[7]: True

请注意,没有异常块,表达式3 in s将对此求值:

Traceback (most recent call last):
(...)
TypeError: gdbm key must be string, not int

事后看来,在这种情况下,最好使用带有预配置值的函数而不是使用类,因为这样会覆盖很多东西,这将浪费您的时间。此外,使用上下文管理器更容易使用,该上下文管理器具有返回文件对象的功能,而不是具有封装文件对象的类(因为当您打开文件架时,实际上是在创建文件)。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

将管道与python“子进程”模块一起使用

在Python中将min(,[,key])与多个参数一起使用

如何在Python中将if语句与数组一起使用?

在AMD GPU中将Python + Theano与OpenCL一起使用

如何在OSX中将OpenCV与python一起使用?

在Python中将Dicom图像与OpenCV一起使用

在Python中将knnMatch与opencv一起使用时出错

在 python 中将类与 Tkinter 一起使用

在多模块Maven项目中将@ project.version @与Liquibase一起使用

在Webpack中将文件加载器与es6模块和打字稿一起使用

无法在多模块项目中将集成覆盖与声纳运行器一起使用

在jedi-vim中将goto与用户定义的模块一起使用

Android Studio与模块一起使用

在MySQL中将WHERE与AS一起使用

在CSS中将*与:not一起使用

Python __repr__的目的

使用 Webpack 与主模块一起构建独立模块

哪些python模块取代urllib2与python 3和flask一起使用?

Python 3类型检查不能与使用键入模块一起使用?

是否可以在Wildfly中将数据源部署描述符与驱动程序模块一起使用?

如何在不使用SQLAlchemy的Flask(Python)中将SQL与Postgresql命令一起使用

为什么python re模块不能与@一起使用?

如何将Mobilenium Python模块与Selenium一起使用

无法将numpy模块导入python文件,但可与终端一起使用

python-ImportError-帮助配置环境以与postgresql模块一起使用

如何将Python OpenID Connect模块与IBM Cloud App ID一起使用?

Python Glob模块不能与多重选择一起使用吗?

Python 3-将kwargs与仅args模块一起使用

将Python模块请求与Sitescout API一起使用时的响应状态代码400