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

  • 相关阅读:
    整数的可除性
    椭圆曲线的基本概念
    数组方法分析-笔记
    JS-作用域
    JS-变量存储
    Web框架-inoic
    圣杯布局
    js,php中的面向对象
    正则
    math对象
  • 原文地址:https://www.cnblogs.com/ydf0509/p/9231969.html
Copyright © 2011-2022 走看看