Python之装饰器(Decorator)
2019-01-19 13:37
232 查看
什么是装饰器
python装饰器(Decorator),采用函数作为输入参数,对该函数进行修饰,使这个函数的功能更加丰富。
装饰器特点
Decoartor可以增加函数的功能,但不用改变函数的内部结构。装饰器的本质是利用闭包和函数的调用。
用法
1、不带参数的装饰器
#_*_coding:utf8_*_ #先来看看没使用装饰器的f1函数运行结果 print "--------未使用装饰器------------" def f1(): print "函数f1" f1() print "--------使用装饰器-------------" #定义装饰器 def decor(func): def wrapper(): #在wrapper这个函数体内加入需要添加的功能 #比如添加打印输出“Decorator” print "Decorator" return func() #返回需要装饰的函数func的结果 return wrapper #用上面定义的装饰器来装饰函数 @decor def f1(): print "函数f1" #调用被装饰的函数f1 f1()
#输出结果 C:\Users\Desktop\py\hshs\Scripts\python.exe C:/Users/Desktop/py/1.py --------未使用装饰器------------ 函数f1 --------使用装饰器------------- Decorator 函数f1 Process finished with exit code 0
基本执行过程:
- 加载decor函数到内存
- 运行@decor
- 执行decor函数,并将 @decor 下面的函数作为decor函数的参数
实际上相当于
f1=decor(f1)
2、带参数的装饰器
#_*_coding:utf8_*_ #基本语法 def decor(func): def wrapper(*args,**kwargs): #增加功能 return func(*args,**kwargs) return wrapper @decor def func(*args,**kwargs): #原函数功能
def decor(func): def wrapper(*args): # 增加功能 print "带参数装饰器" print args return func(*args) return wrapper @decor def f1(name, age, *args): # 原函数功能 print name, age, args f1('hongshu', 20, 'use decorator')
#执行结果 C:\Users\Desktop\py\hshs\Scripts\python.exe C:/Users/Desktop/py/1.py 带参数装饰器 ('hongshu', 20, 'use decorator') hongshu 20 ('use decorator',) Process finished with exit code 0
小结
使用装饰器可以在不改变原函数内部结构的情况下添加自己需要的功能,方便快捷。在使用装饰器之前需要先理解python函数之间的调用以及参数的传递,否则容易出错。
相关文章推荐
- 关于Python的装饰器 decorator
- Python 装饰器 decorator
- python中的装饰器Decorator用法
- Python中的装饰器(decorator)
- Python基础篇之装饰器(decorator)
- Python-装饰器;Decorator模式
- Python中@的用法(Decorator:装饰器)
- python 元类型编程,实现匿名验证器的装饰器AuthenticationDecoratorMeta
- Python 之 decorator 装饰器
- Python进阶之装饰器@decorator
- Python中的装饰器(decorator)
- 【Python】装饰器 - Decorator
- Python中的装饰器(decorator)
- 设计模式-装饰模式-decorator-python
- Python基础-装饰器-Decorator
- Python 入门:装饰器(decorator)、@functools.wraps、@staticmethod、@classmethod
- Python中的装饰器(decorator)
- Python中的装饰器(decorator)
- python 试题:请描述decorator(装饰器)的用法和它的应用场景,如果可以的话,写一个decorator
- 轻量级AOP框架-移植python的装饰器(Decorator)到C#(思考篇)