python之理解装饰器
装饰器是修改其他函数的函数。好处是可以让你的函数更简洁。
一步步理解这个概念:
一、一切皆对象。
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之理解装饰器的更多相关文章
- 理解Python中的装饰器
文章先由stackoverflow上面的一个问题引起吧,如果使用如下的代码: @makebold @makeitalic def say(): return "Hello" 打印出 ...
- 理解Python中的装饰器//这篇文章将python的装饰器来龙去脉说的很清楚,故转过来存档
转自:http://www.cnblogs.com/rollenholt/archive/2012/05/02/2479833.html 这篇文章将python的装饰器来龙去脉说的很清楚,故转过来存档 ...
- python高级之装饰器
python高级之装饰器 本节内容 高阶函数 嵌套函数及闭包 装饰器 装饰器带参数 装饰器的嵌套 functools.wraps模块 递归函数被装饰 1.高阶函数 高阶函数的定义: 满足下面两个条件之 ...
- [python基础]关于装饰器
在面试的时候,被问到装饰器,在用的最多的时候就@classmethod ,@staticmethod,开口胡乱回答想这和C#的static public 关键字是不是一样的,等面试回来一看,哇,原来是 ...
- Python深入05 装饰器
作者:Vamei 出处:http://www.cnblogs.com/vamei 欢迎转载,也请保留这段声明.谢谢! 装饰器(decorator)是一种高级Python语法.装饰器可以对一个函数.方法 ...
- Day04 - Python 迭代器、装饰器、软件开发规范
1. 列表生成式 实现对列表中每个数值都加一 第一种,使用for循环,取列表中的值,值加一后,添加到一空列表中,并将新列表赋值给原列表 >>> a = [0, 1, 2, 3, 4, ...
- 第二篇:python高级之装饰器
python高级之装饰器 python高级之装饰器 本节内容 高阶函数 嵌套函数及闭包 装饰器 装饰器带参数 装饰器的嵌套 functools.wraps模块 递归函数被装饰 1.高阶函数 高阶函 ...
- 简单说明Python中的装饰器的用法
简单说明Python中的装饰器的用法 这篇文章主要简单说明了Python中的装饰器的用法,装饰器在Python的进阶学习中非常重要,示例代码基于Python2.x,需要的朋友可以参考下 装饰器对与 ...
- Python进阶之装饰器
函数也是对象 要理解Python装饰器,首先要明白在Python中,函数也是一种对象,因此可以把定义函数时的函数名看作是函数对象的一个引用.既然是引用,因此可以将函数赋值给一个变量,也可以把函数作为一 ...
随机推荐
- django nginx uwsgi 502 Gateway
前提:腾讯云服务器有个内网ip和外网ip 首先检查使用的端口是否正常可用 1.检查端口是否开放,在腾讯云控制台安全组查看 2.检查防火墙端口是否开放 systemctl start firewalld ...
- BZOJ 1982 / Luogu SP2021: [Spoj 2021]Moving Pebbles (找平衡状态)
这道题在论文里看到过,直接放论文原文吧 在BZOJ上是单组数据,而且数据范围符合,直接int读入排序就行了.代码: #include <cstdio> #include <algor ...
- 如何在Google Maps 添加多个标记
JS如下: (function() { window.onload = function() { // Creating an object literal containin ...
- 本地资源图片无法通过 WXSS 获取,可以使用网络图片,或者 base64,或者使用<image/>标签
在微信小程序开发中,当在CSS中使用背景图片格式为png时就会出现: 只要把png格式改掉就可以或者在<image/>标签里面写,我实测用JPG格式和把图片转成base64是没问题的.
- PHP处理base64编码字符串
接收前端传过来的base64编码后的字符串, 如果是json字符串, 那么PHP使用file_get_contents('php://input'); 来接收. 本次这里是以post传参的形式传bas ...
- 面试必会之ArrayList源码分析&手写ArrayList
简介 ArrayList是我们开发中非常常用的数据存储容器之一,其底层是数组实现的,我们可以在集合中存储任意类型的数据,ArrayList是线程不安全的,非常适合用于对元素进行查找,效率非常高. 线程 ...
- 【luoguP1311 】选择客栈
题目描述 丽江河边有nn家很有特色的客栈,客栈按照其位置顺序从 11到nn编号.每家客栈都按照某一种色调进行装饰(总共 kk 种,用整数 00 ~k-1k−1 表示),且每家客栈都设有一家咖啡店,每家 ...
- Java 面试题 二
1.线程怎么保持同步 关于线程同步(7种方式) --如果朋友您想转载本文章请注明转载地址"http://www.cnblogs.com/XHJT/p/3897440.html"谢谢 ...
- dup2函数
将当前系统中的进程信息打印到文件中 命令行:ps aux > out 将ps得到的信息重定向到out文件中 使用dup2文件在程序中完成. int dup2(int oldfd,int newf ...
- oracle的事务
一.事务 保证数据的一致性,有一组相关的dml语句组成,该组的dml语句要么全部成功,要么全部失败 如:网上转账就是典型的要用事物来处理,用以保证数据的一致性 二.事务和锁 当执行事物操作时(dml语 ...