一、简介

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

二、数据类型

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

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. How to: Debug X++ Code Running in .NET Business Connector [AX 2012]

    This topic has not yet been rated - Rate this topic  http://msdn.microsoft.com/EN-US/library/bb19006 ...

  2. Spark Standalone模式 高可用部署

      本文使用Spark的版本为:spark-2.4.0-bin-hadoop2.7.tgz. spark的集群采用3台机器进行搭建,机器分别是server01,server02,server03. 其 ...

  3. axios封装接口

    我们一般都是在做一个大型项目的时候,需要用到很多接口时,我们为了方便使用,就把接口封装起来. 先安装axios命令 :npm install axios --save 那么思路是什么呢? 首先在src ...

  4. xenserver中linux虚拟机修改启动顺序

    xenserver是思杰的一款类似于vmware ESXI的虚拟化平台,或者说虚拟化操作系统,上面可以安装许多虚拟机,但是当你装完linux虚拟机,你会发现一个问题,不能像windows vm那样直接 ...

  5. 图解 Spring 循环依赖,写得太好了!

    Spring如何解决的循环依赖,是近两年流行起来的一道Java面试题. 其实笔者本人对这类框架源码题还是持一定的怀疑态度的. 如果笔者作为面试官,可能会问一些诸如"如果注入的属性为null, ...

  6. Spring扩展之二:ApplicationListener

    1.介绍 用于监听应用程序事件的接口. 子接口:GenericApplicationListener,SmartApplicationListener. 通过ApplicationEvent类和App ...

  7. C#高级编程之特性

    特性定义 MSDN的描述:使用特性,可以有效地将元数据或声明性信息与代码(程序集.类型.方法.属性等)相关联. 将特性与程序实体相关联后,可以在运行时使用反射这项技术查询特性. 参考此处作者的解释 h ...

  8. 创建Spring Cloud聚合项目

    使用maven创建单一项目的时候通常用不到聚合项目,创建spring cloud项目时候,由于下面都是一个一个微服务,每个服务对应一个项目,这就需要用到聚合项目,方便对依赖和项目之间的关系进行管理,使 ...

  9. MySQL存储索引InnoDB数据结构为什么使用B+树,而不是其他树呢?

    InnoDB的一棵B+树可以存放多少行数据? 答案:约2千万 为什么是这么多? 因为这是可以算出来的,要搞清楚这个问题,先从InnoDB索引数据结构.数据组织方式说起. 计算机在存储数据的时候,有最小 ...

  10. 早期javac编译器优化

    学习<深入了解Java虚拟机>有一段时间了,大概理解了Java从源代码编译到执行出结果的过程,也能明确的知道Java是半解释性语言.在执行源代码时,先通过Javac编译器对源代码进行词法分 ...