Python之函数装饰器和捕获异常

函数装饰器

函数装饰器的语法

python有一个特殊的性质不同于其他大多数的编程语言,就是函数本身可以作为一个参数传递给另外一个函数。这样就衍生出了函数装饰器。
函数装饰器的语法如下:
函数装饰器函数
@函数装饰器函数名(注意不带小括号)
被装饰函数
调用被装饰函数。
说明:这里是将被装饰函数作为参数传递给装饰器函数,调用被装饰函数的时候实际上是在调用装饰器函数。

装饰器函数的特点

1、装饰器函数传入的参数是一个函数。
2、装饰器函数内嵌一个函数,并且返回内嵌函数(被装饰函数有参数的时候要有内嵌函数接受参数)。

定义一个装饰器

[root@localhost python]# cat /python/decorator.py 
#!/usr/bin/env python
#-*- coding:utf-8 -*-
def decorator(func):
   def innerfun(*args):
      print("开始计算")
      func(*args)
      print("计算结束")
   return innerfun

@decorator
def add(*args):
   list1=[]
   list1.extend(list(args))
   total=0
   for j in range(0,len(list1)):
      total = total+list1[j]
   print('{}相加元素和为{}'.format([list1],total))

add(1,2,3)

执行

[root@localhost python]# python decorator.py 
开始计算
[[1, 2, 3]]相加元素和为6
计算结束

装饰器和捕获异常

故意传错参数,执行看输出。

[root@localhost python]# cat /python/decorator.py 
#!/usr/bin/env python
#-*- coding:utf-8 -*-
def decorator(func):
   def innerfun(*args):
      print("开始计算")
      func(*args)
      print("计算结束")
   return innerfun

@decorator
def add(*args):
   list1=[]
   list1.extend(list(args))
   total=0
   for j in range(0,len(list1)):
      total = total+list1[j]
   print('{}相加元素和为{}'.format([list1],total))

add(1,2,'a')

报错输出很乱,并且输出比较难以理解。

[root@localhost python]# python decorator.py 
开始计算
Traceback (most recent call last):
  File "decorator.py", line 20, in <module>
    add(1,2,'a')
  File "decorator.py", line 6, in innerfun
    func(*args)
  File "decorator.py", line 17, in add
    total = total+list1[j]
TypeError: unsupported operand type(s) for +: 'int' and 'str'

在装饰器里捕获异常,并且指定异常后的输出。

[root@localhost python]# cat decorator.py 
#!/usr/bin/env python
#-*- coding:utf-8 -*-
def decorator(func):
   def innerfun(*args):
      try:
         print("开始计算")
         func(*args)
         print("计算结束")
      except:
         print('请输入正确的参数')
   return innerfun

@decorator
def add(*args):
   list1=[]
   list1.extend(list(args))
   total=0
   for j in range(0,len(list1)):
      total = total+list1[j]
   print('{}相加元素和为{}'.format([list1],total))

add(1,2,'a')

输出一目了然。

[root@localhost python]# python decorator.py 
开始计算
请输入正确的参数

这只是一个简单的演示,实战中怎么应用装饰器请参考我的另外一篇博文python调用libvirt API和装饰器应用

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

时空无限

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值