来个简单的装饰器
def cached_method_result(fun): """方法的结果缓存装饰器""" @wraps(fun) def inner(self, *args, **kwargs): if not hasattr(fun, 'result'): result = fun(self, *args, **kwargs) fun.result = result fun_name = fun.__name__ setattr(self.__class__, fun_name, result) setattr(self, fun_name, result) return result else: return fun.result return inner
使用方式:
class MongoMixin(object): @property @utils_ydf.decorators.cached_method_result def mongo_16_client(self): mongo_var = pymongo.MongoClient(app_config.connect_url) return mongo_var
无论怎么调用mongo_16_client这个属性,都不会多次连接。
本文介绍了一种简单的方法结果缓存装饰器,并通过实例展示了如何避免重复连接MongoDB,提高程序效率。

1374

被折叠的 条评论
为什么被折叠?



