zoukankan      html  css  js  c++  java
  • python缓存装饰器,第二种方式(二)

    来个简单的装饰器

    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这个属性,都不会多次连接。

  • 相关阅读:
    log4j
    hashContext
    sql语句
    css样式
    作业七:(二)疑问解答
    作业七:(1)翻译
    结对编程作业
    软件优缺点评价(补交)
    C#程序分析
    VS2013安装及测试练习
  • 原文地址:https://www.cnblogs.com/ydf0509/p/9231969.html
Copyright © 2011-2022 走看看