来个简单的装饰器
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这个属性,都不会多次连接。