python 之 函数 装饰器
5.8 装饰器
1 开放封闭原则 软件一旦上线后,就应该遵循开放封闭原则,即对修改源代码是封闭的,对功能的扩展是开放的 也就是说我们必须找到一种解决方案: 能够在不修改一个功能源代码以及调用方式的前提下,为其加上新功能 原则如下: 1、不修改源代码 2、不修改调用方式 目的: 在遵循1和2原则的基础上扩展新功能
装饰器: 装饰器即在不修改被装饰对象源代码与调用方式的前提下,为被装饰器对象添加新功能,装饰器与被装饰的对象均可以是任意可调用的对象
装饰器 ===》函数 被装饰的对象 ===》函数
5.81 无参装饰器举例
import time
def index():
time.sleep(3)
print('welcome to index page')
def outter(func): #func=最原始的index
def wrapper():
start_time=time.time()
func()
stop_time=time.time()
print(stop_time-start_time)
return wrapper
index=outter(index) # 新的index=wrapper
index() #wrapper()
welcome to index page
3.0000429153442383
5.82 无参装饰器升级
import time
def index():
time.sleep(1)
print('welcome to index page')
return 122
def home(name):
time.sleep(2)
print('welcome %s to home page' %name)
#==============装饰器
def timmer(func): #func=最原始的index
def wrapper(*args,**kwargs):
start_time=time.time()
res=func(*args,**kwargs) #调用最原始的index
stop_time=time.time()
print(stop_time-start_time)
return res
return wrapper
index=timmer(index) # 新的index=wrapper
home=timmer(home) #新的home=wrapper
# ==========================================
res=index() #res=wrapper()
print(res)
res=home(name='egon') #res=wrapper(name='egon')
print(res)
5.83 无参装饰器模板:
def index():
pass
#==============装饰器
def outer(func):
def inner(*args,**kwargs):
res=func(*args,**kwargs)
return res
return inner
index=outer(index)
# ==========================================
res=index()
print(res)
使用:在被装饰对象正上方单独一行,@无参装饰器名
@无参装饰器名
def foo():
pass
5.84 装饰器语法糖
import time
def timmer(func):
def wrapper(*args,**kwargs):
start_time=time.time()
res=func(*args,**kwargs)
stop_time=time.time()
print(stop_time-start_time)
return res
return wrapper
@timmer #index=timmer(index)
def index():
time.sleep(1)
print('welcome to index page')
return 122
@timmer # home=timmer(home)
def home(name):
time.sleep(2)
print('welcome %s to home page' %name)
index()
home('egon')
5.85 叠加装饰器
import time
current_user={
'username':None,
}
def auth(func): # func=index
def wrapper(*args,**kwargs):
if current_user['username']:
print('已经登陆过了')
res=func(*args,**kwargs)
return res
uname=input('用户名>>: ').strip()
pwd=input('密码>>: ').strip()
if uname == 'egon' and pwd == '':
print('登陆成功')
current_user['username']=uname
res=func(*args,**kwargs)
return res
else:
print('用户名或密码错误')
return wrapper
def timmer(func):
def wrapper(*args,**kwargs):
start_time=time.time()
res=func(*args,**kwargs)
stop_time=time.time()
print(stop_time-start_time)
return res
return wrapper
@timmer # timmer 统计的是auth+index的执行时间
@auth
def index():
time.sleep(1)
print('welcome to index page')
return 122
index()
5.86 有参装饰器
import time
current_user={
'username':None
}
def auth(engine): # engine='file' #添加一层函数传engine值
def auth2(func): # func=index
def wrapper(*args,**kwargs):
if engine == 'file':
if current_user['username']:
print('已经登陆过了')
res=func(*args,**kwargs)
return res
uname=input('用户名>>: ').strip()
pwd=input('密码>>: ').strip()
if uname == 'egon' and pwd == '':
print('登陆成功')
current_user['username']=uname
res=func(*args,**kwargs)
return res
else:
print('用户名或密码错误')
elif engine == 'mysql':
print('基于MyQL的认证')
elif engine == 'ldap':
print('基于LDAP的认证')
return wrapper
return auth2
#auth_src=auth('ldap')
#@auth_src
@auth('ldap') # @auth2 #index=auth2(index) #index=wrapper
def index():
time.sleep(1)
print('welcome to index page')
return 122
index() # wrapper()
5.87 有参装饰器模板
def outter2(x,y,z):
def outter(func):
def wrapper(*args,**kwargs):
res=func(*args,**kwargs)
return res
return wrapper
return outter
@outer2(1,2,3)
# ==========================================
def index():
pass
res=index()
print(res)
使用:在被装饰对象正上方单独一行,@有参装饰器名(1,2,3) @有参装饰器名(1,2,3)
def foo():
pass
python 之 函数 装饰器的更多相关文章
- python基础—函数装饰器
python基础-函数装饰器 1.什么是装饰器 装饰器本质上是一个python函数,它可以让其他函数在不需要做任何代码变动的前提下增加额外功能. 装饰器的返回值是也是一个函数对象. 装饰器经常用于有切 ...
- python基础-----函数/装饰器
函数 在Python中,定义一个函数要使用def语句,依次写出函数名.括号.括号中的参数和冒号:,然后,在缩进块中编写函数体,函数的返回值用return语句返回. 函数的优点之一是,可以将代码块与主程 ...
- Decorator——Python初级函数装饰器
最近想整一整数据分析,在看一本关于数据分析的书中提到了(1)if __name__ == '__main__' (2)列表解析式 (3)装饰器. 先简单描述一下前两点,再详细解说Python初级的函数 ...
- python 复习函数 装饰器
# 函数 —— 2天 # 函数的定义和调用 # def 函数名(形参): #函数体 #return 返回值 #调用 函数名(实参) # 站在形参的角度上 : 位置参数,*args,默认参数(陷阱),* ...
- day11 python之函数装饰器
一,什么是装饰器? 装饰器本质上就是一个python函数,他可以让其他函数在不需要做任何代码变动的前提下,增加额外的功能,装饰器的返回值也是一个函数对象. 装饰器的应用场景:比如插入日志,性能测试,事 ...
- python 匿名函数&装饰器
匿名函数 关键字lambda表示匿名函数,冒号前面的x表示函数参数匿名函数有个限制,就是只能有一个表达式,不用写return,返回值就是该表达式的结果. >>> list(map(l ...
- python闭包函数&装饰器
一.函数引用 函数可以被引用 函数可以被赋值给一个变量 def hogwarts(): print("hogwarts") # hogwarts() # 函数调用 print(ho ...
- Python之函数装饰器
在实际中,我们可能需要在不改变函数源代码和调用方式的情况下,为函数添加一些新的附加功能,能够实现这种功能的函数我们将其称之为装饰器.装饰器本质上其实还是是一个函数,用来装饰其它函数,为函数添加一些附加 ...
- Python中函数装饰器及练习
)]) ,,],)
随机推荐
- jquery插件pagination实现分页
1.效果 2.HTML代码 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind=" ...
- DIV+CSS常见问题的14条原因分析
当你在一个浏览器里面做好,在其他浏览器里面却完全不是那么回事情. 很多时候,我们就只是去修补下,或者利用各个浏览器对代码支持的不一致,进行针对各个浏览器进行不同的定义. 其实浏览器的不兼容,我们往 ...
- [CPP - STL] functor刨根问底儿
作为STL六大组件之一,在STL源代码及其应用中,很多地方使用了仿函数(functor),尤其在关联型容器(如set.map)以及algorithm(如find_if.count_if等)中.虽然已经 ...
- backbone测试代码
一.入门测试 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www. ...
- java 接口自动化测试之数据请求的简单封装
我们自己用java写接口自动化测试框架或者做个接口自动化测试平台的话,是需要自己进行相关的请求的,因此我们需要简单的封装下httpclient,我新建了一个http工具类,将get方法和post方法进 ...
- zabbix数据库创建初始化
MariaDB [(none)]> create database zabbix character set utf8; MariaDB [(none)]> grant all privi ...
- html5--5-14 阶段小练习:绘制太极图案
html5--5-14 阶段小练习:绘制太极图案 学习要点 运用前几节课的知识完成一个小练习 这个图案有多种不同的绘制方法,这里只做一个简单的演示,练习的时候可以自己思考一下,尝试其他的方法,或者对这 ...
- python学习笔记:第二天(基本数据类型)
Python3 基本数据类型 1.标准数据类型 Python3中有六个标准的数据类型:Number(数字).String(字符串).List(列表).Tuple(元组).Sets(集合).Dictio ...
- 值域线段树 (玲珑OJ 1117)
点击打开题目链接 题目意思很简单: 1.插入x 2.把小于x的数变成x 3.把大于x的数变成x 4.求集合中第x小数 5.求集合中小于x的数个数 思路: 线段树,节点是值的分数,你可以离散,也可以不离 ...
- HDU1852 Beijing 2008(快速幂+特殊公式)
As we all know, the next Olympic Games will be held in Beijing in 2008. So the year 2008 seems a lit ...