zoukankan      html  css  js  c++  java
  • python 装饰器(八):装饰器实例(五)函数装饰器装饰类以及类方法

    函数装饰器装饰类

    单例模式

    from functools import wraps
    
    def singleton(cls):
        instances = {}
    
        @wraps(cls)
        def get_instance(*args, **kw):
            if cls not in instances:
                instances[cls] = cls(*args, **kw)
            return instances[cls]
        return get_instance

    函数装饰器装饰类方法

    添加异常处理

    def catch_exception(origin_func):
        def wrapper(self, *args, **kwargs):
            try:
                u = origin_func(self, *args, **kwargs)
                return u
            except Exception:
                self.revive() #不用顾虑,直接调用原来的类的方法
                return 'an Exception raised.'
        return wrapper
    class Test(object):
        def __init__(self):
            pass
        def revive(self):
            print('revive from exception.')
            # do something to restore
        @catch_exception
        def read_value(self):
            print('here I will do something.')
            # do something.

     带参数

    def catch_exception(level):
        def decorator(origin_func):
            def wrapper(self, *args, **kwargs):
                print(level)
                try:
                    u = origin_func(self, *args, **kwargs)
                    return u
                except Exception:
                    self.revive() #不用顾虑,直接调用原来的类的方法
                    return 'an Exception raised.'
            return wrapper
        return decorator
    
    
    class Test(object):
        def __init__(self):
            pass
        def revive(self):
            print('revive from exception.')
            # do something to restore
        @catch_exception(level='error')
        def read_value(self):
            print('here I will do something.')
            # do something.
            # 
    
    if __name__ == '__main__':
        t = Test()
        t.read_value()
  • 相关阅读:
    使用方法GetPostBackEventReference 得到回发脚本
    超实用的Linux/Unix快捷键大汇总
    Http 之Get/Post请求区别
    使用ASP启动/停止指定WEB站点
    使用ASP在IIS创建WEB站点的函数
    CSS+JS 仿MSN TAB选项卡
    防止圖片在WEB頁面上下載
    asp定时生成静态HTML的代码
    jQuery Slide Show – jQuery幻灯片效果
    Debian 5.0.5 正式版
  • 原文地址:https://www.cnblogs.com/qiu-hua/p/12950280.html
Copyright © 2011-2022 走看看