Python全栈-day11-函数3
装饰器
1.开放封闭原则
通常情况下,软件一旦上线就应该遵循开放封闭原则,即对修改封闭、对扩展开放
扩展开放需遵循两个原则:
1)不修改源代码
2)不修改原函数的调用方式
2.装饰器
器指的是工具,装饰指的是为被装饰对象添加新功能;即不修改源代码和调用方式的基础上为被装饰函数添加新功能
注意:装饰器和被装饰对象可以是任意可调用的对象
装饰器模板:
'''
def outer(func):
def wrapper(*args,**kwargs):
res = func(*args,**kwargs)
return res
return wrapper
'''
3.无参装饰器
import time
def outer(func):
def wrapper(*args,**kwargs):
strt_time = time.time()
res = func(*args,**kwargs)
stop_time = time.time()
print('index run time is %s' %(stop_time-strt_time))
return res
return wrapper @outer
def index():
time.sleep(1)
print('welcome to index page...')
return 'ahah' @outer
def home(name):
time.sleep(2)
print('home page...',name) # 闭包函数实现
# 不改变原函数的调用方式和源代码
index() home('zhang')
4.多个装饰器叠加使用
import time
db_file = '锁定用户.txt'
def timer(func):
def wrapper(*args,**kwargs):
strt_time = time.time()
res = func(*args,**kwargs)
stop_time = time.time()
print('index run time is %s' %(stop_time-strt_time))
return res
return wrapper
def auth(func):
def wrapper(*args,**kwargs):
tag = True
while tag:
user_inp = input('输入用户名>>').strip()
pwd = input('输入密码>>')
with open(r'%s' % db_file,'rt',encoding='utf-8') as f:
for line in f:
user_info = line.strip('\n').split(',')
if user_inp == user_info[0] and pwd == user_info[1]:
print('logging successful...')
tag = False
break
else:
print('logging false,please tay again...')
res = func(*args,**kwargs)
return res
return wrapper
# @timer
# @auth
# 当timer装饰在前时,统计的时间是auth + index的运行时间
# @auth
# @timer
# 当timer装饰在后时,统计的时间是index的运行时间
@timer
@auth
def index():
time.sleep(1)
print('welcome to index page...')
return 'ahah'
index()
5.含参装饰器
import time
current_user={
'username':None,
# 'login_time':None
}
def auth(engine):
# engine='file'
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('ldap') #@auth2 #index=auth2(index) #index=wrapper
def index():
time.sleep(1)
print('welcome to index page')
return 10
index() # wrapper()
Python全栈-day11-函数3的更多相关文章
- python全栈开发 生成器 :生成器函数,推导式及生成器表达式
python 全栈开发 1.生成器函数 2.推导式 3.生成器表达式 一.生成器函数 1.生成器: 生成器的本质就是迭代器 (1)生成器的特点和迭代器一样.取值方式和迭代器一样(__next__(), ...
- python全栈开发之匿名函数和递归函数
python 匿名函数和递归函数 python全栈开发,匿名函数,递归函数 匿名函数 lambda函数也叫匿名函数,即函数没有具体的名称.是为了解决一些功能很简单需求而设计的一句话函数.如下: #这段 ...
- 老男孩Python全栈第2期+课件笔记【高清完整92天整套视频教程】
点击了解更多Python课程>>> 老男孩Python全栈第2期+课件笔记[高清完整92天整套视频教程] 课程目录 ├─day01-python 全栈开发-基础篇 │ 01 pyth ...
- Python全栈【Socket网络编程】
Python全栈[socket网络编程] 本章内容: Socket 基于TCP的套接字 基于UDP的套接字 TCP粘包 SocketServer 模块(ThreadingTCPServer源码剖析) ...
- Python全栈开发【面向对象进阶】
Python全栈开发[面向对象进阶] 本节内容: isinstance(obj,cls)和issubclass(sub,super) 反射 __setattr__,__delattr__,__geta ...
- Python全栈开发【面向对象】
Python全栈开发[面向对象] 本节内容: 三大编程范式 面向对象设计与面向对象编程 类和对象 静态属性.类方法.静态方法 类组合 继承 多态 封装 三大编程范式 三大编程范式: 1.面向过程编程 ...
- Python全栈开发【模块】
Python全栈开发[模块] 本节内容: 模块介绍 time random os sys json & picle shelve XML hashlib ConfigParser loggin ...
- Python全栈开发【基础四】
Python全栈开发[基础四] 本节内容: 匿名函数(lambda) 函数式编程(map,filter,reduce) 文件处理 迭代器 三元表达式 列表解析与生成器表达式 生成器 匿名函数 lamb ...
- Python全栈开发【基础三】
Python全栈开发[基础三] 本节内容: 函数(全局与局部变量) 递归 内置函数 函数 一.定义和使用 函数最重要的是减少代码的重用性和增强代码可读性 def 函数名(参数): ... 函数体 . ...
- Python全栈考试-部分试题(精选)
Python全栈考试(一) Python全栈考试(一) 1.执行 Python 脚本的两种方式 答:1.>>python ../pyhton.py 2. >>python.py ...
随机推荐
- [development][PCRE] old PCRE
介绍, man手册 txt版 http://www.pcre.org/original/pcre.txt html版 http://www.pcre.org/original/doc/html/pcr ...
- [troubleshoot][automake] automake编译的时候发生死循环
在某台特有设备上,编译dssl工程时,竟然发生了死循环. https://github.com/tony-caotong/libdssl 错误日志如下: checking zlib.h presenc ...
- [linux] 对一个虚拟机的研究
今天拿到了一个vmware的虚拟机硬盘镜像,是其他公司的演示产品. 启动之后是带着ubuntu字样的grub.进入系统之后也不是shell,而是一个定制的命令行.所以如果想了解细节的话,只能单独挂硬盘 ...
- idhttp与cookie
用关键词“idhttp cookie”在各大搜索引擎得到的结果,大多千篇一律,如果你搜索到这一篇,恭喜你,你有福了. 以下内容测试环境:delphi2007, winxp sp3, indy10. ...
- 转:JAVA中解决Filter过滤掉css,js,图片文件等问题
原文链接:https://www.cnblogs.com/ermeng/p/6440966.html public void doFilter(ServletRequest request, Serv ...
- 内部排序->交换排序->快速排序
文字描述 快速排序是对起泡排序的一种改进.它的基本思想是,通过一趟排序将待排序记录分割成独立的两部分,其中一部分记录的关键字均比另一部分记录的关键字小,则可分别对这两部分记录继续进行排序,以达到整个 ...
- java IO(二)大文件复制
package cn.sasa.demo3; import java.io.FileInputStream; import java.io.FileOutputStream; import java. ...
- word2vec参数理解
之前写了对word2vec的一些简单理解,实践过程中需要对其参数有较深的了解: class gensim.models.word2vec.Word2Vec(sentences=None,size=10 ...
- nodejs 学习三 异步和同步
同步函数 for (let i = 0; i < 10; i ++) { setTimeout(() => { console.log(`${i} ______ ${new Date}`) ...
- 10.3-uC/OS-III内部任务管理(TCB)
任务控制块 TCB 1.任务控制块是被uC/OS-III用于维护任务的一个结构体.每个任务都必须有自己的 TCB. uC/OS-III 在 RAM 中分配 TCB.当调用uC/OS-III提供的与任务 ...