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 之 函数 装饰器的更多相关文章

  1. python基础—函数装饰器

    python基础-函数装饰器 1.什么是装饰器 装饰器本质上是一个python函数,它可以让其他函数在不需要做任何代码变动的前提下增加额外功能. 装饰器的返回值是也是一个函数对象. 装饰器经常用于有切 ...

  2. python基础-----函数/装饰器

    函数 在Python中,定义一个函数要使用def语句,依次写出函数名.括号.括号中的参数和冒号:,然后,在缩进块中编写函数体,函数的返回值用return语句返回. 函数的优点之一是,可以将代码块与主程 ...

  3. Decorator——Python初级函数装饰器

    最近想整一整数据分析,在看一本关于数据分析的书中提到了(1)if __name__ == '__main__' (2)列表解析式 (3)装饰器. 先简单描述一下前两点,再详细解说Python初级的函数 ...

  4. python 复习函数 装饰器

    # 函数 —— 2天 # 函数的定义和调用 # def 函数名(形参): #函数体 #return 返回值 #调用 函数名(实参) # 站在形参的角度上 : 位置参数,*args,默认参数(陷阱),* ...

  5. day11 python之函数装饰器

    一,什么是装饰器? 装饰器本质上就是一个python函数,他可以让其他函数在不需要做任何代码变动的前提下,增加额外的功能,装饰器的返回值也是一个函数对象. 装饰器的应用场景:比如插入日志,性能测试,事 ...

  6. python 匿名函数&装饰器

    匿名函数 关键字lambda表示匿名函数,冒号前面的x表示函数参数匿名函数有个限制,就是只能有一个表达式,不用写return,返回值就是该表达式的结果. >>> list(map(l ...

  7. python闭包函数&装饰器

    一.函数引用 函数可以被引用 函数可以被赋值给一个变量 def hogwarts(): print("hogwarts") # hogwarts() # 函数调用 print(ho ...

  8. Python之函数装饰器

    在实际中,我们可能需要在不改变函数源代码和调用方式的情况下,为函数添加一些新的附加功能,能够实现这种功能的函数我们将其称之为装饰器.装饰器本质上其实还是是一个函数,用来装饰其它函数,为函数添加一些附加 ...

  9. Python中函数装饰器及练习

    )])   ,,],)

随机推荐

  1. 用live555将内网摄像机视频推送到外网服务器,附源码

    最近很多人问,如何将内网的摄像机流媒体数据发布到公网,如果用公网与局域网间的端口映射方式太过麻烦,一个摄像机要做一组映射,而且不是每一个局域网都是有固定ip地址,即使外网主机配置好了每一个摄像机的映射 ...

  2. jquery 使用ajax,正常返回后,不执行success的问题

    背景: 在使用到jQuery的ajax时,如果指定了dataType为json,老是不执行success回调,而是执行了error回调函数. 原因: 然后继续下载了几个jquery版本,如1.3.2, ...

  3. xcode环境变量设置(转载)

    一般我们在xcode里面配置包含工程目录下头文件的时候,都要关联着相对路径和绝对路径,如果只是自己用这个项目,用绝对路径的问题不大,但是如果你把工程发给别人,别人就要在改这个绝对路径,这时候绝对路径的 ...

  4. [noip2014day2-T1]无线网路发射器选址

    随着智能手机的日益普及,人们对无线网的需求日益增大.某城市决定对城市内的公共场所覆盖无线网. 假设该城市的布局为由严格平行的129条东西向街道和129条南北向街道所形成的网格状,并且相邻的平行街道之间 ...

  5. Codeforces Round #376 (Div. 2) D. 80-th Level Archeology —— 差分法 + 线段扫描法

    题目链接:http://codeforces.com/contest/731/problem/D D. 80-th Level Archeology time limit per test 2 sec ...

  6. SCAU 还有两个东西 —— 异或

    竞赛题 F  还有两个东西 Time Limit:400MS  Memory Limit:65535K 题型: 编程题   语言: 无限制 描述 给出n( n >= 2 )个整数,其中有 2 个 ...

  7. ios系统的特点

    iOS优势 1). 比较稳定,因为他是一个完全封闭的系统,不开源,但是这个系统有他自己严格管理体系,比如app store的app应用:他有自己的评审规则,另外很多软件是需要收费的,这在一定程度上也说 ...

  8. [转载]支付宝钱包手势密码破解实战(root过的手机可直接绕过手势密码)

    /* *转自http://blog.csdn.net/hu3167343/article/details/36418063 *本文章由 莫灰灰 编写,转载请注明出处. *作者:莫灰灰    邮箱: m ...

  9. php之创建jsonp接口调数据

    jsonp跨域访问数据 首先在php内写jsonp调用接口 <?php//设置头部文件类型为json header('Content-type: application/json'); //将r ...

  10. bzoj 3771 Triple —— FFT

    题目:https://www.lydsy.com/JudgeOnline/problem.php?id=3771 令多项式的系数是方案数,次数是值: 设 a(x) 为一个物品的多项式,即 a[w[i] ...