一、简介

装饰器是是修改其它函数功能的函数;其意义是让其他函数在不修改任何代码的前提下增加额外功能

二、数据类型

首先我们来看一段简单的代码:

from types import MethodType,FunctionType

class A(object):
def f1(self):
pass def f2(a, b):
return a + b if __name__ == '__main__':
a = A()
print(type(a.f1)) #<class 'method'>
print(type(f2)) #<class 'function'>

结论:不难看出,f1的类型是方法,f2的类型是函数;那有人会问了解这个有啥作用呢?其实了解这个有助于我们下面了解装饰器的原理

三、认识装饰器:

let's go... 我们来看一个案例:

def B():
print("now you are inside the B() function") def sing():
return "now you are in the sing() function" def eat():
return "now you are in the eat() function" def sleep():
return "now you are in the sleep() function" print(sing())
print(eat())
print(sleep())
#输出的结果为:
now you are inside the hi() function
now you are in the sing() function
now you are in the eat() function
now you are in the sleep() function

结论:那现在我们知道了可以在函数中定义另外的函数。也就是说:我们可以创建嵌套的函数

我们再接着看一段代码,如何让函数作为参数传给另外一个函数的:

def A():
return "hi 小陈!" def doSomethingBeforeA(func):
print("I am doing some boring work before executing A()")
print(func()) #执行:
doSomethingBeforeA(A)
#输出结果:
I am doing some boring work before executing A()
hi 小陈!

什么?你还没看懂,那我们再看一个案例:

from types import FunctionType

def text():
return "Hello world!" def add_itali(func: FunctionType):
def new_func():
#print("now you are in the new_func() function")
return text() #返回text()函数
return new_func

#执行:
print(type(add_itali(text)))
print(add_itali(text)())
#输出结果:
<class 'function'>
Hello world!

难么现在你看懂了么?如果还是没懂,没关系我们再来看看下一段代码:

def new_decorator(func):
def wrapTheFunction():
print("I am doing some boring work before executing func()")
func()
print("I am doing some boring work after executing func()")
return wrapTheFunction def requiring_decoration():
print("I am the function which needs decoration")

#执行:
requiring_decoration() #输出结果:
I am the function which needs decoration
#执行:
new_decorator(requiring_decoration)() #输出结果:
I am doing some boring work before executing func()
I am the function which needs decoration
I am doing some boring work after executing func()

有人会有疑问,new_decorator(requiring_decoration)()为哈后面要加“()”呢去,请继续往下看:

#执行:
print(new_decorator(requiring_decoration)) #输出结果:
function new_decorator.<locals>.wrapTheFunction at 0x000001FC976BB620>

为什么会这样呢,请随我娓娓道来。。。

四、装饰器的优雅使用:

那么好,我们把上面代码再优化下,用装饰器常用的表达方式表示出来:

def new_decorator(func):
def wrapTheFunction():
print("I am doing some boring work before executing func()")
func() #被装饰的函数
print("I am doing some boring work after executing func()")
return wrapTheFunction @new_decorator
def requiring_decoration():
print("I am the function which needs decoration")
#执行:
requiring_decoration() #输出结果:
I am doing some boring work before executing func()
I am the function which needs decoration
I am doing some boring work after executing func()

老铁们,现在你们懂了么,没懂我们再来看一段代码:

#需求:  <b><i> Hello World!</i></b>
from types import FunctionType

def add_bold(func: FunctionType):
def new_func():
return f"<b>{func()}</b>"
return new_func def add_itali(func: FunctionType):
def new_func():
return f"<i>{func()}</i>"
return new_func @add_itali # 语法
@add_bold
def text():
return "Hello world!"
#执行:
print(text()) #输出结果:
<i><b>Hello world!</b></i>

五、总结:

#语法:装饰器就是一个函数
def 装饰器名(func):
def wrapper(*args, **kwargs):
// 要做的装饰 ,,省略若干代码
result = func(*args,**kwargs)
return result
return wrapper

最新文章

  1. TaintDroid深入剖析之启动篇
  2. cookie多次点赞效果
  3. 新版汉诺塔(UVa10795 - A Different Task)
  4. Java基础之在窗口中绘图——移动曲线的控制点(CurveApplet 3 moving the control points)
  5. Testing Round #8 A. IQ Test 水题
  6. 将tomcat设为开机自动启动
  7. UVa 101 (模拟) The Blocks Problem
  8. check、continue、exit的区别
  9. hihocoder 1077线段树
  10. javascript笔记4之运算符
  11. SQL Server 空间监测
  12. 应用程序无法正常启动0xc000007b
  13. Notification和Activity交互
  14. Android 音频管理器AudioManager
  15. linux 网络之 bond 网卡模式
  16. Spring Boot的数据访问 之Spring Boot + jpa的demo
  17. benthos stream 处理工具说明
  18. WCF 和 ASP.NET Web API
  19. 180724-统计JVM进程中线程数两种方式小记
  20. sql分割字符串详解

热门文章

  1. Git使用push命令卡住?
  2. Spring Security 实战干货:客户端OAuth2授权请求的入口
  3. 《精通Spring4.x企业应用开发实战》第二章
  4. 2.1 自定义日志系统-log4net
  5. ohmyzsh的安装过程中失败拒绝连接问题的解决
  6. java版飞机大战代码
  7. Linux标准输入、标准输出、错误输出
  8. Linux学习 - 02 使用 - Centos8 - 『更换rpm/epel包源为国内源』
  9. mac中怎么完成移动硬盘分区这个操作
  10. 如何使用ABBYY FineReader 用户词典识别专业术语?