一、简介

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

二、数据类型

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

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

python装饰器基础及应用的更多相关文章

  1. Python装饰器基础及运行时间

    一.装饰器基础 装饰器是可调用的对象,其参数是另一个函数(被装饰的函数).装饰器可能会处理被装饰的函数,然后把他返回,或者将其替换成另一个函数或可调用对象. eg:decorate装饰器 @decor ...

  2. Python装饰器基础

    一.Python装饰器引入 讲 Python 装饰器前,我想先举个例子,虽有点污,但跟装饰器这个话题很贴切. 每个人都有的内裤主要功能是用来遮羞,但是到了冬天它没法为我们防风御寒,咋办?我们想到的一个 ...

  3. Python基础(五) python装饰器使用

    这是在Python学习小组上介绍的内容,现学现卖.多练习是好的学习方式. 第一步:最简单的函数,准备附加额外功能 # -*- coding:gbk -*- '''示例1: 最简单的函数,表示调用了两次 ...

  4. Python开发基础-Day7-闭包函数和装饰器基础

    补充:全局变量声明及局部变量引用 python引用变量的顺序: 当前作用域局部变量->外层作用域变量->当前模块中的全局变量->python内置变量 global关键字用来在函数或其 ...

  5. [python 基础]python装饰器(一)添加functools获取原函数信息以及functools.partial分析

    python装饰器学习的时候有两点需要注意一下 1,被装饰器装饰的函数取其func.__name__和func.func_doc的时候得到的不是被修饰函数的相关信息而是装饰器wrapper函数的doc ...

  6. python装饰器通俗易懂的解释!

    1.python装饰器 刚刚接触python的装饰器,简直懵逼了,直接不懂什么意思啊有木有,自己都忘了走了多少遍Debug,查了多少遍资料,猜有点点开始明白了.总结了一下解释得比较好的,通俗易懂的来说 ...

  7. Python 装饰器学习

    Python装饰器学习(九步入门)   这是在Python学习小组上介绍的内容,现学现卖.多练习是好的学习方式. 第一步:最简单的函数,准备附加额外功能 1 2 3 4 5 6 7 8 # -*- c ...

  8. Python装饰器由浅入深

    装饰器的功能在很多语言中都有,名字也不尽相同,其实它体现的是一种设计模式,强调的是开放封闭原则,更多的用于后期功能升级而不是编写新的代码.装饰器不光能装饰函数,也能装饰其他的对象,比如类,但通常,我们 ...

  9. (转载)Python装饰器学习

    转载出处:http://www.cnblogs.com/rhcad/archive/2011/12/21/2295507.html 这是在Python学习小组上介绍的内容,现学现卖.多练习是好的学习方 ...

随机推荐

  1. Mongoose Guide(转)

    转自:http://www.w3c.com.cn/mongoose-guide Queries 文件可以通过一些静态辅助模型的方法检索. 任何涉及 指定 查询 条件的模型方法,有两种执行的方式: 当一 ...

  2. knn-demo

    from __future__ import print_functionfrom numpy import *# 导入科学计算包numpy和运算符模块operatorimport operatorf ...

  3. Python学习笔记2:基本数据类型

    Python中的变量不需要声明.每个变量在使用前都必须赋值,变量赋值以后该变量才会被创建. 在 Python 中,变量就是变量,它没有类型,我们所说的"类型"是变量所指的内存中对象 ...

  4. 通过JS判断当前浏览器的类型

    通过JS判断当前浏览器的类型,对主流浏览器Chrome.Edge.Firefox.UC浏览器.QQ浏览器.360浏览器.搜狗浏览器的userAgent属性值来判断用户使用的是什么浏览器. 不同浏览器的 ...

  5. Docker - 解决创建 tomcat 容器镜像却无法访问页面的问题

    问题背景 查看 tomcat 镜像 docker images 运行并创建 tomcat 容器 docker -d -p 8888:8080 --name=tomcat2 tomcat:latest ...

  6. Vuex原理详解

    一.Vuex是什么 Vuex是专门为Vuejs应用程序设计的状态管理工具.它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生改变.它集中于MVC模式中的Model层 ...

  7. maven 笔记2

    maven 中央工厂的位置:D:\dubbo\apache-maven-3.2.5\lib D:\dubbo\apache-maven-3.2.5\lib pom-4.0.0.xml reposito ...

  8. Go语言配置管理神器——Viper中文教程

    Viper是适用于Go应用程序的完整配置解决方案.它被设计用于在应用程序中工作,并且可以处理所有类型的配置需求和格式. Viper Viper是适用于Go应用程序的完整配置解决方案.它被设计用于在应用 ...

  9. this.getClass().getResource("") url path file 区别

    首先注意 "/word/appointDismiss.docx" 前面一定要加 /,有一次我就是忘记加/ 查了半天错, 不能写成 "word/appointDismiss ...

  10. 【python爬虫】用requests库模拟登陆人人网

    说明:以前是selenium登陆取cookie的方法比较复杂,改用这个 """ 用requests库模拟登陆人人网 """ import r ...