python学习之-- 装饰器
高阶函数+嵌套函数 == 装饰器
什么是装饰器: 其实也是一个函数。
功能:为其他的函数添加附加功能
原则:不能修改被装饰的函数的源代码和调用方式 学习装饰器前首先要明白以下3条事项:
1:函数 即 “变量” (什么意思呢,就是说我们定义的一个函数,其中函数名就是一个变量,函数体就是存于内存的数据)。
def foo(): #函数名就相当于变量
print('test') #函数体就相当于内容
类似于:x(变量) = 1(内容)
内容实际存储于内存,变量相当于门牌号(映射内存内容)。
实例
def foo():
print('in the foo')
bar()
def bar():
print('in the bar')
foo()
2:高阶函数
条件1:把一个函数名当作实参传给另一个函数(在不修改被装饰函数源码的情况下为其添加附加功能)
举例:当调用执行函数fun1时候,会把bar函数当作实参传入,在fun1函数内对形参进行执行fun() -> bar ->bar()
def bar():
print('in the bar')
def fun1(fun):
print('start) #进行装饰
fun() #执行的核心函数
print('end') #进行装饰
fun1(bar)
条件2:函数的返回值中包含n>0个函数。(不修改函数的调用方式)
举例:
def bar():
time.sleep(3)
print('in the bar')
def test2(func):
print(func)
return func
bar = test2(bar)
bar() #这里就是源函数被修饰后,再次调用返回被修饰后的结果
3:嵌套函数:一个函数体内创建另一个函数,最外层函数相当于全局变量,函数内部的所有函数都相当于局部变量,只在局部作用域有效。
举例:
def foo():#这里相当于全局变量
print('in the foo')
def bar(): # 这里相当于局部变量,只在局部作用域有效。
print('in the bar')
bar() #执行局部变量
foo() #执行函数调用
装饰器实例1:先加载timer函数体到内存,然后在@timer相当于将test1函数作为实参传递给timer函数,最后调用test1()函数,就相当于执行timer函数内的warpper函数,将内部执行结果返回 给test1
def timer(func): # func = test1
def warpper():
start_time = time.time()
func()
end_time = time.time()
print('the function time is %s' %(stop_time-start_time)
return warpper()
@timer #test1=timer(test1)
def test1():
time.sleep(3)
print('in the test')
test1() #这里test1就相当于在执行warpper函数
装饰器实例2带参数
import time
def timer(fun): # 传入每个被装饰的函数名
def bar(*args,**kwargs): # 传入每个被装饰的函数参数
start = time.time()
fun(*args,**kwargs)
end = time.time()
print('time:%s' % (end-start))
return bar
@timer
def test1():
time.sleep(1)
print('in the test1')
@timer
def test2(name,age):
print('test2:',name,age)
test1()
test2('jeck',age=22)
装饰器-补充:如何返回被装饰的函数的return值
user,passwd = 'jeck','abc123'
def auth(func):
def warpper(*args,**kwargs):
username = input('username')
password = input('password')
if username == user and password == passwd:
print('user has passwd authentication')
mess = func(*args,**kwargs) # 这里返回func函数的return值
return mess # 这里将mess的值返回给warpper
else:
exit('error password')
return warpper # 返回warpper值,包含mess的 def index():
print('welcome to index page')
@auth
def home():
print('welcome to home page')
return 'from home' #这里的return如何通过装饰器返回
@auth
def bbs():
print('welcome to bbs page')
index()
print(home()) #这里要用print打印使用return返回的值
bbs()
装饰器--高级版,这里让上面例子里home用普通验证,bbs用ldap验证
import time
name,pwd = 'jeck',''
def auth_type(auth_type):#认证模式参数传入
def auth(fun):
def warpper(*args,**kwargs):
if auth_type == 'local': # 根据认证模式执行函数
name = input('name:')
passwd = input('passwd:')
if name == name and passwd == pwd:
print('welcome logname :%s' % name)
content = fun(*args,**kwargs)
return content
elif auth_type == 'ldap': #根据认证模式执行函数
print('ldap')
content = fun(*args,**kwargs)
return content
return warpper
return auth
def index():
print('welcome to index page')
@auth_type(auth_type = 'local')# 增加认证模式的选择
def home():
print('welcome to home page')
return 'from home' #需要获取这里的return返回
@auth_type(auth_type = 'ldap') # 增加认证模式的选择
def bbs(name,age):
print('welcome to bbs page')
return name,age
index()
print(home())
print(bbs('bard',age=22))
python学习之-- 装饰器的更多相关文章
- python学习笔记--装饰器
1.首先是一个很无聊的函数,实现了两个数的加法运算: def f(x,y): print x+y f(2,3) 输出结果也ok 5 2.可是这时候我们感觉输出结果太单一了点,想让代码的输出多一点看起来 ...
- python 学习分享-装饰器篇
本篇内容为偷窃的~哈哈,借用一下,我就是放在自己这里好看. 引用地址:http://www.cnblogs.com/rhcad/archive/2011/12/21/2295507.html 第一步: ...
- python学习之装饰器-
python的装饰器 2018-02-26 在了解python的装饰器之前我们得了解python的高阶函数 python的高阶函数我们能返回一个函数名并且能将函数名作为参数传递 def outer() ...
- python学习day14 装饰器(二)&模块
装饰器(二)&模块 #普通装饰器基本格式 def wrapper(func): def inner(): pass return func() return inner def func(): ...
- Python学习 :装饰器
装饰器(函数) 装饰器作为一个函数,可以为其他函数在不修改原函数代码的前提下添加新的功能 装饰器的返回值是一个函数对象.它经常用于有切面需求的场景,比如:插入日志.性能测试.事务处理.缓存.权限校验等 ...
- Python学习笔记--装饰器的实验
装饰器既然可以增加原来函数的功能,那能不能改变传给原函数的参数呢? 我们实验一下,先上代码: #!/usr/bin/env python # -*- coding: utf-8 -*- # @Date ...
- 6月4日 python学习总结 装饰器复习
1. 装饰器的原理以及为什么要使用装饰器 在代码运行期间动态增加功能的方式,称之为"装饰器"(Decorator). 在不影响原代码结构的情况下为其添加功能 2. 装饰器的基本 ...
- python学习 day13 装饰器(一)&推导式
装饰器&推导式 传参位置参数在前,关键词参数在后 函数不被调用内部代码不被执行 函数在被调用的时候,每次都会开辟一个新的内存地址,互不干扰 #经典案例 def func(num): def i ...
- Python学习之装饰器进阶
函数知识回顾: 函数的参数分为:实参和形参. 实参:调用函数的时候传入的参数: 形参:分为3种(位置参数.默认参数.动态传参) 位置参数:必须传值 def aaa(a,b): print(a,b) a ...
随机推荐
- iOS 从相册中拿到 图片名 ,截取后缀,图片名
//从路径中获得完整的文件名 (带后缀) 对从相册中取出的图片,视频都有效. NSString *fileName = [filePath lastPathComponent]; //获得文件名 (不 ...
- 应用程序员眼中的数据库管理系统:API+数据库语言
应用程序员眼中的数据库管理系统:API+数据库语言 sqlite3_open_v2 https://www.cnblogs.com/cchust/p/5121559.html
- uva1352 Colored Cubes LA3401
白书第一章例题8 好麻烦! 正方体每面编号为0-5,那么根据顶点和正面,就能确定形态.一共6*4=24种形态. P[i]表示编号i所在位置.比如P[1]=3,表示第二面转到了第四面. 就可以表示出所有 ...
- QTreeWidgetItem封装
#include "qtreewighthelper.h" QTreeWidgetItem* AddQTreeWidgetItemChild(QTreeWidgetItem* pa ...
- 欧拉函数 || LightOJ 1370 Bi-shoe and Phi-shoe
给出x,求最小的y使y的欧拉函数大于等于x *解法:i).求出1e6之内的数的欧拉函数,遍历找 ii).求比x大的第一个质数——因为每个质数n的欧拉函数都是n-1 wa一次是因 ...
- url跳转路径参数获取
function getUrlParam1(name){ //正则表达式过滤 var reg = new RegExp("(^|&)" + name + "=([ ...
- fossil 使用
~$ fossil updateCannot figure out who you are! Consider using the --usercommand line option, setting ...
- Ztree 多选,显示勾选的路径
项目要求,需要向后台传递已经勾选的路径,如 l1-a, l1-l3-c,l1-l3-d;(如果是全选状态则只传递全选状态的路径,不传子节点). 具体可以参考jQ Ztree 的 v3.5 版本 Me ...
- 定位 absolute和relative比较
absolute:脱离原来位置定位.是相对于最近的有定位的父级进行定位;如果没有有定位的父级元素,就相对文档进行定位 relative:保留原来位置进行定位,相对于自己原来的位置进行定位 下面举两个例 ...
- encodeURI()与decodeURI()等转码方法
只针对文本编码 encodeURI() 只针对文本解码 decodeURI()针对文本和特殊字符的编码 encodeURIComponent()针对文本和特殊字符的解码 decodeURIComp ...