Python 装饰器装饰类中的方法

https://blog.csdn.net/hesi9555/article/details/70224911

 

title: Python 装饰器装饰类中的方法
comments: true
date: 2017-04-17 20:44:31
tags: ['Python', 'Decorate']
category: ['Python']
---

目前在中文网上能搜索到的绝大部分关于装饰器的教程,都在讲如何装饰一个普通的函数。本文介绍如何使用Python的装饰器装饰一个类的方法,同时在装饰器函数中调用类里面的其他方法。本文以捕获一个方法的异常为例来进行说明。

有一个类Test, 它的结构如下:

  1.  
    class Test(object):
  2.  
    def __init__(self):
  3.  
    pass
  4.  
     
  5.  
    def revive(self):
  6.  
    print('revive from exception.')
  7.  
    # do something to restore
  8.  
     
  9.  
    def read_value(self):
  10.  
    print('here I will do something.')
  11.  
    # do something.

在类中有一个方法read_value(),这个方法在多个地方被调用。由于某些原因,方法read_value有可能随机抛出Exception导致程序崩溃。所以需要对整个方法做try ... except处理。最丑陋的做法如下面的代码所示:

  1.  
    class Test(object):
  2.  
    def __init__(self):
  3.  
    pass
  4.  
     
  5.  
    def revive(self):
  6.  
    print('revive from exception.')
  7.  
    # do something to restore
  8.  
     
  9.  
    def read_value(self):
  10.  
    try:
  11.  
    print('here I will do something.')
  12.  
    # do something.
  13.  
    except Exception as e:
  14.  
    print(f'exception {e} raised, parse exception.')
  15.  
    # do other thing.
  16.  
    self.revive()

这样写虽然可以解决问题,但是代码不Pythonic。

使用装饰器来解决这个问题,装饰器函数应该写在类里面还是类外面呢?答案是,写在类外面。那么既然写在类外面,如何调用这个类的其他方法呢?

首先写出一个最常见的处理异常的装饰器:

  1.  
    def catch_exception(origin_func):
  2.  
    def wrapper(*args, **kwargs):
  3.  
    try:
  4.  
    u = origin_func(*args, **kwargs)
  5.  
    return u
  6.  
    except Exception:
  7.  
    return 'an Exception raised.'
  8.  
    return wrapper
  9.  
     
  10.  
     
  11.  
    class Test(object):
  12.  
    def __init__(self):
  13.  
    pass
  14.  
     
  15.  
    def revive(self):
  16.  
    print('revive from exception.')
  17.  
    # do something to restore
  18.  
     
  19.  
    @catch_exception
  20.  
    def read_value(self):
  21.  
    print('here I will do something.')
  22.  
    # do something.

这种写法,确实可以捕获到origin_func()的异常,但是如果在发生异常的时候,需要调用类里面的另一个方法来处理异常,这又应该怎么办?答案是给wrapper增加一个参数:self.

代码变为如下形式:

  1.  
    def catch_exception(origin_func):
  2.  
    def wrapper(self, *args, **kwargs):
  3.  
    try:
  4.  
    u = origin_func(self, *args, **kwargs)
  5.  
    return u
  6.  
    except Exception:
  7.  
    self.revive() #不用顾虑,直接调用原来的类的方法
  8.  
    return 'an Exception raised.'
  9.  
    return wrapper
  10.  
     
  11.  
     
  12.  
    class Test(object):
  13.  
    def __init__(self):
  14.  
    pass
  15.  
     
  16.  
    def revive(self):
  17.  
    print('revive from exception.')
  18.  
    # do something to restore
  19.  
     
  20.  
    @catch_exception
  21.  
    def read_value(self):
  22.  
    print('here I will do something.')
  23.  
    # do something.

只需要修改装饰器定义的部分,使用装饰器的地方完全不需要做修改。

下图为正常运行时的运行结果:
正常运行

下图为发生异常以后捕获并处理异常:
发生异常

通过添加一个self参数,类外面的装饰器就可以直接使用类里面的各种方法,也可以直接使用类的属性

 

posted on 2018-04-25 18:46  枫飞飞  阅读(249)  评论(0编辑  收藏  举报