基于Python 装饰器装饰类中的方法实例
作者:hesi9555 时间:2023-10-11 04:10:22
title: Python 装饰器装饰类中的方法
comments: true
date: 2017-04-17 20:44:31
tags: ['Python', 'Decorate']
category: ['Python']
---
目前在中文网上能搜索到的绝大部分关于装饰器的教程,都在讲如何装饰一个普通的函数。本文介绍如何使用Python的装饰器装饰一个类的方法,同时在装饰器函数中调用类里面的其他方法。本文以捕获一个方法的异常为例来进行说明。
有一个类Test, 它的结构如下:
class Test(object):
def __init__(self):
pass
def revive(self):
print('revive from exception.')
# do something to restore
def read_value(self):
print('here I will do something.')
# do something.
在类中有一个方法read_value(),这个方法在多个地方被调用。由于某些原因,方法read_value有可能随机抛出Exception导致程序崩溃。所以需要对整个方法做try ... except处理。最丑陋的做法如下面的代码所示:
class Test(object):
def __init__(self):
pass
def revive(self):
print('revive from exception.')
# do something to restore
def read_value(self):
try:
print('here I will do something.')
# do something.
except Exception as e:
print(f'exception {e} raised, parse exception.')
# do other thing.
self.revive()
这样写虽然可以解决问题,但是代码不Pythonic。
使用装饰器来解决这个问题,装饰器函数应该写在类里面还是类外面呢?答案是,写在类外面。那么既然写在类外面,如何调用这个类的其他方法呢?
首先写出一个最常见的处理异常的装饰器:
def catch_exception(origin_func):
def wrapper(*args, **kwargs):
try:
u = origin_func(*args, **kwargs)
return u
except Exception:
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.
这种写法,确实可以捕获到origin_func()的异常,但是如果在发生异常的时候,需要调用类里面的另一个方法来处理异常,这又应该怎么办?答案是给wrapper增加一个参数:self.
代码变为如下形式:
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.
只需要修改装饰器定义的部分,使用装饰器的地方完全不需要做修改。
下图为正常运行时的运行结果:
下图为发生异常以后捕获并处理异常:
通过添加一个self参数,类外面的装饰器就可以直接使用类里面的各种方法,也可以直接使用类的属性。
来源:https://blog.csdn.net/hesi9555/article/details/70224911
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
python编写WAF与Sqlmap结合实现指纹探测
![](https://img.aspxhome.com/file/2023/6/103796_0s.png)
Python中matplotlib如何改变画图的字体
![](https://img.aspxhome.com/file/2023/9/127589_0s.png)
超越质检员——看图购beta版的思考
![](https://img.aspxhome.com/file/UploadPic/20094/15/090410_gotaobao_01-41s.png)
ASP伪静态页简单教程
教你利用pygame模块制作跳跃小球小游戏
![](https://img.aspxhome.com/file/2023/7/123557_0s.png)
Python中的 enumerate和zip详情
![](https://img.aspxhome.com/file/2023/8/107118_0s.png)
pycharm创建scrapy项目教程及遇到的坑解析
![](https://img.aspxhome.com/file/2023/2/66782_0s.png)
VScode中集成Git命令详解
![](https://img.aspxhome.com/file/2023/7/112077_0s.png)
使用python实现正则匹配检索远端FTP目录下的文件
Python使用MySQLdb for Python操作数据库教程
MySQL 开窗函数
![](https://img.aspxhome.com/file/2023/4/86874_0s.png)
关于python的对象序列化介绍
Oracle连续相同数据的统计
![](https://img.aspxhome.com/file/2023/8/64858_0s.png)
mysql or走索引加索引及慢查询的作用
![](https://img.aspxhome.com/file/2023/7/112667_0s.png)
Python+Tkinter制作在线个性签名工具
![](https://img.aspxhome.com/file/2023/3/123793_0s.png)
python将ansible配置转为json格式实例代码
![](https://img.aspxhome.com/file/2023/3/118403_0s.png)
MySQL慢查询优化解决问题
mysql5.5数据库data目录迁移方法详解
![](https://img.aspxhome.com/file/2023/2/121572_0s.jpg)
pytorch model.cuda()花费时间很长的解决
![](https://img.aspxhome.com/file/2023/3/86143_0s.jpg)