装饰器

Posted xiezuodd

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了装饰器相关的知识,希望对你有一定的参考价值。

"""
装饰器:
什么是装饰器
装饰:就是增加的,原本没有的,用来装饰的
器:器物,器具。
装饰器就是一个增加功能的函数,被装饰的也是一个函数。
装饰器是干嘛用的
装饰器是将一个新增的功能装饰在一个函数上。
怎么定义装饰器
在不改变原函数的源代码,不改变它的调用方式的前提下,新增一个功能。
def outer(func):
def timer(*args,**kwargs):
‘新增功能‘
res = func(*args,**kwargs)
return res
return timer

无参装饰器
def outer(func):
def timer():
‘新增功能‘
res = func()
return res
return timer
有参装饰器
def outer(func):
def timer(*args,**kwargs):
‘新增功能‘
res = func(*args,**kwargs)
return res
return timer
装饰器的语法糖
def outer(func):
def timer(*args,**kwargs):
‘新增功能‘
res = func(*args,**kwargs)
return res
return timer
@outer test=outer(test)
def test():
print(‘hello world‘)

"""

以上是关于装饰器的主要内容,如果未能解决你的问题,请参考以下文章

python 装饰器:装饰器实例类装饰器(装饰函数)

装饰器、装饰器类与类装饰器(三)

Python进阶装饰器(Decorator)

python 装饰器:装饰器实例内置装饰器

python 装饰器:装饰器实例内置装饰器

TS之装饰器