装饰器

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的更多相关文章

  1. python全栈开发 生成器 :生成器函数,推导式及生成器表达式

    python 全栈开发 1.生成器函数 2.推导式 3.生成器表达式 一.生成器函数 1.生成器: 生成器的本质就是迭代器 (1)生成器的特点和迭代器一样.取值方式和迭代器一样(__next__(), ...

  2. python全栈开发之匿名函数和递归函数

    python 匿名函数和递归函数 python全栈开发,匿名函数,递归函数 匿名函数 lambda函数也叫匿名函数,即函数没有具体的名称.是为了解决一些功能很简单需求而设计的一句话函数.如下: #这段 ...

  3. 老男孩Python全栈第2期+课件笔记【高清完整92天整套视频教程】

    点击了解更多Python课程>>> 老男孩Python全栈第2期+课件笔记[高清完整92天整套视频教程] 课程目录 ├─day01-python 全栈开发-基础篇 │ 01 pyth ...

  4. Python全栈【Socket网络编程】

    Python全栈[socket网络编程] 本章内容: Socket 基于TCP的套接字 基于UDP的套接字 TCP粘包 SocketServer 模块(ThreadingTCPServer源码剖析) ...

  5. Python全栈开发【面向对象进阶】

    Python全栈开发[面向对象进阶] 本节内容: isinstance(obj,cls)和issubclass(sub,super) 反射 __setattr__,__delattr__,__geta ...

  6. Python全栈开发【面向对象】

    Python全栈开发[面向对象] 本节内容: 三大编程范式 面向对象设计与面向对象编程 类和对象 静态属性.类方法.静态方法 类组合 继承 多态 封装 三大编程范式 三大编程范式: 1.面向过程编程 ...

  7. Python全栈开发【模块】

    Python全栈开发[模块] 本节内容: 模块介绍 time random os sys json & picle shelve XML hashlib ConfigParser loggin ...

  8. Python全栈开发【基础四】

    Python全栈开发[基础四] 本节内容: 匿名函数(lambda) 函数式编程(map,filter,reduce) 文件处理 迭代器 三元表达式 列表解析与生成器表达式 生成器 匿名函数 lamb ...

  9. Python全栈开发【基础三】

    Python全栈开发[基础三]  本节内容: 函数(全局与局部变量) 递归 内置函数 函数 一.定义和使用 函数最重要的是减少代码的重用性和增强代码可读性 def 函数名(参数): ... 函数体 . ...

  10. Python全栈考试-部分试题(精选)

    Python全栈考试(一) Python全栈考试(一) 1.执行 Python 脚本的两种方式 答:1.>>python ../pyhton.py 2. >>python.py ...

随机推荐

  1. py文件传输

    本文参考:http://blog.163.com/kongdelu2009@yeah/blog/static/1119952072009102562126194/ 发送端程序: # -*- codin ...

  2. 分析占用了大量 CPU 处理时间的是Java 进程中哪个线程

    下面是详细步骤: 1. 首先确定进程的 ID ,可以使用 jps -v 或者 top 命令直接查看 2. 查看该进程中哪个线程占用大量 CPU,执行 top -H -p [PID] 结果如下: 可以发 ...

  3. 图->存储结构->邻接多重表

    文字描述 邻接多重表是无向图的另一种链式存储结构. 虽然邻接表是无向图的一种很有效的存储结构,在邻接表中容易求得顶点和边的各种信息. 但是,在邻接表中每一条边(vi,vj)有两个结点,分别在第i个和第 ...

  4. C++生成静态库

    //StaticMath.h #include <iostream> class StaticMath { public: //StaticMath(void); //~StaticMat ...

  5. ASMCMD报错解决:sh: /u01/app/11.2.4/grid/bin/clsecho: No such file or directory

    sh: /u01/app/11.2.4/grid/bin/clsecho: No such file or directory 在登录asmcmd时报此错误,尝试解决,刷新oracle_sid也不行 ...

  6. LeetCode 806 Number of Lines To Write String 解题报告

    题目要求 We are to write the letters of a given string S, from left to right into lines. Each line has m ...

  7. Shiro 自定义角色 认证

    转载,原博文的地址在:https://ailongni.iteye.com/blog/2086022 由于Shiro filterChainDefinitions中 roles默认是and,/** = ...

  8. java 线程(六)死锁

    package cn.sasa.demo4; public class ThreadDemo { public static void main(String[] args){ DeadLockRun ...

  9. tomcat去掉项目名称

    进入tomcat的conf目录,查看server.xml,找到<Host></Host>,在里面添加<Context path="" docBase= ...

  10. InnoDB log file 设置多大合适?

    简介: 数据库的东西,往往一个参数就牵涉N多知识点.所以简单的说一下.大家都知道innodb是支持事务的存储引擎.事务的四个特性ACID即原子性(atomicity),一致性(consistency) ...