python with用法举例
2018-08-22 17:41
92 查看
我们知道在操作文件对象的时候可以这么写
with open('a.txt') as f: '代码块'
上述叫做上下文管理协议,即with语句,为了让一个对象兼容with语句,必须在这个对象的类中声明__enter__和__exit__方法
使用举例
import shelve class ShelveUtil(object): """ 使用Shelve存储提取对象 """ def __init__(self, file): self.file_name = file def save(self, key, value): """ 存储对象 :param key: :param value: :return: """ self.file_obj[key] = value def load(self, key): """ 获得对象 :param key: :return: """ return self.file_obj[key] def load_keys(self): """ 返回所有key :return: """ return list(self.file_obj.keys()) def del_obj(self, key): """ 删除object :return: """ del self.file_obj[key] def __enter__(self): print("enter") self.file_obj = shelve.open(self.file_name) return self def __exit__(self, exc_type, exc_val, exc_tb): print("exit") self.file_obj.close() return True if __name__ == '__main__': a = {'a': 1, 'b': 2} with ShelveUtil('a.db') as s: s.save('a', a) print(s.load('a'))
输出
enter {'a': 1, 'b': 2} exit
相关文章推荐
- 关于python中enumerate和zip函数的用法及举例
- Python with用法实例
- Python with语句用法
- 举例讲解Python中的list列表数据结构用法
- python with用法
- python中with和contextlib的用法
- python中with...as的用法
- python With关键字用法(2)
- Python异常模块traceback用法举例
- Python中zip()函数用法举例
- Python中with...as的用法
- Python中的集合:set与frozenset用法举例
- Python With 用法
- 举例简单讲解Python中的数据存储模块shelve的用法
- Python异常模块traceback用法举例
- Python中zip()函数用法举例
- python的with用法
- 举例讲解Python中的算数运算符的用法
- Python中的with...as的用法
- Python的with...as的用法