函数装饰器
函数装饰器的语法
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和装饰器应用