装饰器是修改其他函数的函数。好处是可以让你的函数更简洁。

一步步理解这个概念:

一、一切皆对象。

def hi(name="yasoob"):
return "hi " + name print(hi())
# output: 'hi yasoob' # 我们甚至可以将一个函数赋值给一个变量,比如
greet = hi
# 我们这里没有在使用小括号,因为我们并不是在调用hi函数
# 而是在将它放在greet变量里头。我们尝试运行下这个 print(greet())
# output: 'hi yasoob' # 如果我们删掉旧的hi函数,看看会发生什么!
del hi
print(hi())
#outputs: NameError print(greet())
#outputs: 'hi yasoob'

二、函数中定义函数

def hi(name="yasoob"):
print("now you are inside the hi() function") def greet():
return "now you are in the greet() function" def welcome():
return "now you are in the welcome() function" print(greet())
print(welcome())
print("now you are back in the hi() function") hi()
#output:now you are inside the hi() function
# now you are in the greet() function
# now you are in the welcome() function
# now you are back in the hi() function # 上面展示了无论何时你调用hi(), greet()和welcome()将会同时被调用。
# 然后greet()和welcome()函数在hi()函数之外是不能访问的,比如: greet()
#outputs: NameError: name 'greet' is not defined

三、函数中返回函数

def hi(name="yasoob"):
def greet():
return "now you are in the greet() function" def welcome():
return "now you are in the welcome() function" if name == "yasoob":
return greet
else:
return welcome a = hi()
print(a)
#outputs: <function greet at 0x7f2143c01500> #上面清晰地展示了`a`现在指向到hi()函数中的greet()函数
#现在试试这个 print(a())
#outputs: now you are in the greet() function

四、函数作为参数传递

def hi():
return "hi yasoob!" def doSomethingBeforeHi(func):
print("I am doing some boring work before executing hi()")
print(func()) doSomethingBeforeHi(hi)
#outputs:I am doing some boring work before executing hi()
# hi yasoob!

五、第一个装饰器

def a_new_decorator(a_func):

    def wrapTheFunction():
print("I am doing some boring work before executing a_func()") a_func() print("I am doing some boring work after executing a_func()") return wrapTheFunction def a_function_requiring_decoration():
print("I am the function which needs some decoration to remove my foul smell") a_function_requiring_decoration()
#outputs: "I am the function which needs some decoration to remove my foul smell" a_function_requiring_decoration = a_new_decorator(a_function_requiring_decoration)
#now a_function_requiring_decoration is wrapped by wrapTheFunction() a_function_requiring_decoration()
#outputs:I am doing some boring work before executing a_func()
# I am the function which needs some decoration to remove my foul smell
# I am doing some boring work after executing a_func()

六、使用@符号

@a_new_decorator
def a_function_requiring_decoration():
"""Hey you! Decorate me!"""
print("I am the function which needs some decoration to "
"remove my foul smell") a_function_requiring_decoration()
#outputs: I am doing some boring work before executing a_func()
# I am the function which needs some decoration to remove my foul smell
# I am doing some boring work after executing a_func() #the @a_new_decorator is just a short way of saying:
a_function_requiring_decoration = a_new_decorator(a_function_requiring_decoration)

七、遇到问题

print(a_function_requiring_decoration.__name__)
# Output: wrapTheFunction

八、解决问题

from functools import wraps

def a_new_decorator(a_func):
@wraps(a_func)
def wrapTheFunction():
print("I am doing some boring work before executing a_func()")
a_func()
print("I am doing some boring work after executing a_func()")
return wrapTheFunction @a_new_decorator
def a_function_requiring_decoration():
"""Hey yo! Decorate me!"""
print("I am the function which needs some decoration to "
"remove my foul smell") print(a_function_requiring_decoration.__name__)
# Output: a_function_requiring_decoration

九、蓝本规范

from functools import wraps
def decorator_name(f):
@wraps(f)
def decorated(*args, **kwargs):
if not can_run:
return "Function will not run"
return f(*args, **kwargs)
return decorated @decorator_name
def func():
return("Function is running") can_run = True
print(func())
# Output: Function is running can_run = False
print(func())
# Output: Function will not run

十、使用场景

(1)授权(Authorization)

from functools import wraps

def requires_auth(f):
@wraps(f)
def decorated(*args, **kwargs):
auth = request.authorization
if not auth or not check_auth(auth.username, auth.password):
authenticate()
return f(*args, **kwargs)
return decorated

python之理解装饰器的更多相关文章

  1. 理解Python中的装饰器

    文章先由stackoverflow上面的一个问题引起吧,如果使用如下的代码: @makebold @makeitalic def say(): return "Hello" 打印出 ...

  2. 理解Python中的装饰器//这篇文章将python的装饰器来龙去脉说的很清楚,故转过来存档

    转自:http://www.cnblogs.com/rollenholt/archive/2012/05/02/2479833.html 这篇文章将python的装饰器来龙去脉说的很清楚,故转过来存档 ...

  3. python高级之装饰器

    python高级之装饰器 本节内容 高阶函数 嵌套函数及闭包 装饰器 装饰器带参数 装饰器的嵌套 functools.wraps模块 递归函数被装饰 1.高阶函数 高阶函数的定义: 满足下面两个条件之 ...

  4. [python基础]关于装饰器

    在面试的时候,被问到装饰器,在用的最多的时候就@classmethod ,@staticmethod,开口胡乱回答想这和C#的static public 关键字是不是一样的,等面试回来一看,哇,原来是 ...

  5. Python深入05 装饰器

    作者:Vamei 出处:http://www.cnblogs.com/vamei 欢迎转载,也请保留这段声明.谢谢! 装饰器(decorator)是一种高级Python语法.装饰器可以对一个函数.方法 ...

  6. Day04 - Python 迭代器、装饰器、软件开发规范

    1. 列表生成式 实现对列表中每个数值都加一 第一种,使用for循环,取列表中的值,值加一后,添加到一空列表中,并将新列表赋值给原列表 >>> a = [0, 1, 2, 3, 4, ...

  7. 第二篇:python高级之装饰器

    python高级之装饰器   python高级之装饰器 本节内容 高阶函数 嵌套函数及闭包 装饰器 装饰器带参数 装饰器的嵌套 functools.wraps模块 递归函数被装饰 1.高阶函数 高阶函 ...

  8. 简单说明Python中的装饰器的用法

    简单说明Python中的装饰器的用法 这篇文章主要简单说明了Python中的装饰器的用法,装饰器在Python的进阶学习中非常重要,示例代码基于Python2.x,需要的朋友可以参考下   装饰器对与 ...

  9. Python进阶之装饰器

    函数也是对象 要理解Python装饰器,首先要明白在Python中,函数也是一种对象,因此可以把定义函数时的函数名看作是函数对象的一个引用.既然是引用,因此可以将函数赋值给一个变量,也可以把函数作为一 ...

随机推荐

  1. es高级用法之冷热分离

    背景 用户需求:近期数据查询速度快,较远历史数据运行查询速度慢? 对于开发人员而言即数据的冷热分离,实现此功能有2个前提条件: 硬件:处理速度不同的硬件,最起码有读写速度不同的硬盘,如SSD.机械硬盘 ...

  2. fsLayui缓存使用

    概述 缓存主要使用在编辑或查看页面查询数据的方式,通过后端servlet接口获取数据还是通过前端缓存获取.缓存可以使用在实时性要求不高的上面.减少后端servlet请求. 使用步骤 配置支持缓存 需要 ...

  3. 《深入理解Java虚拟机》之(二、垃圾收集器与内存分配策略)

    程序计数器.虚拟机栈.本地方法栈3个区域随线程而生,随线程而灭,这几个区域的内存分配和回收都具备确定性,不需要过多考虑回收的问题,因为方法结束或者线程结束时,内存自然就跟着回收了,而java堆和方法区 ...

  4. Boosting算法(一)

    本章全部来自于李航的<统计学>以及他的博客和自己试验.仅供个人复习使用. Boosting算法通过改变训练样本的权重,学习多个分类器,并将这些分类器进行线性组合,提高分类性能.我们以Ada ...

  5. elementUI el-date-picker 时间范围设置 固定时间段可选 配置

    https://blog.csdn.net/sinat_37255207/article/details/91793889 <el-date-picker v-model="start ...

  6. [2019牛客多校第二场][E. MAZE]

    题目链接:https://ac.nowcoder.com/acm/contest/882/E 题目大意:有一个\(n\times m\)的01矩阵,一开始可以从第一行的一个点出发,每次可以向左.向右. ...

  7. 云主机用samba服务实现和windows共享文件

    最近刚刚入坑了百度云的云主机BCC,准备在云主机上实现samba服务,映射到本机来当硬盘使用,可是一直怎么试都不成功,后来咨询客服之后才知道samba默认使用的端口445端口被运营商封禁了,只好更改端 ...

  8. 【Wince-截图】对Wince进行截图

    对Wince进行截图 方法一 使用Wince桌面助手对Wince进行截图 PC通过USB成功连接到手持机 打开Wince桌面助手CERHOST.exe程序 File->Capture进行截图 C ...

  9. vue项目实现详情页后退缓存之前的数据

    vue项目实现详情页后退缓存之前的数据 2019年02月19日 14:54:57 不想写代码的程序员 阅读数:244   一.需要缓存的内容: 1.后退缓存条件查询的数据 2.后退缓存分页信息 二.实 ...

  10. php实现浏览器大文件分片上传

    PHP用超级全局变量数组$_FILES来记录文件上传相关信息的. 1.file_uploads=on/off 是否允许通过http方式上传文件 2.max_execution_time=30 允许脚本 ...