我们知道在操作文件对象的时候可以这么写
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