Python全栈-day11-函数3

时间:2022-09-14 21:25:19

装饰器

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. 新课程开始的第二天,HTML基础制作

    天正式开始学习HTML的基础制作,有简单的指令开始入手. 第一天的学习,因为基础,所以觉得还算简单,主要是对网页背景.图片.文字.表格等的编辑,和一部分链接的使用. 由下面的的一个事例,通过所学的简单 ...

  2. queue

    http://www.codeforces.com/contest/625/problem/E

  3. UIButton 点击后变灰

    +(UIButton *)getBlueButtonWithTitle:(NSString *)aTitle{ UIButton *button = [UIButton buttonWithType: ...

  4. CSS练习一(模仿163邮箱登陆)

    // '); code = code.replace(/&/g, '&'); return code; }; var runCode = function (code) { if (c ...

  5. CI源码引用使用--php引用demo,静态变量和引用关系

    CI源码引用使用在Common.php中,加载配置和类的方法 function &test() {     static $a = '';     if (!$a) {         $a ...

  6. AIX 常用命令和知识

      BOOTLIST:#bootlist -m normal -o (查看bootlist)#bootlist -m normal (设置bootlist为空,谁要在我机器上执行我就要哭了)#boot ...

  7. 玩转spring boot——websocket

    前言 QQ这类即时通讯工具多数是以桌面应用的方式存在.在没有websocket出现之前,如果开发一个网页版的即时通讯应用,则需要定时刷新页面或定时调用ajax请求,这无疑会加大服务器的负载和增加了客户 ...

  8. 设计模式 | 抽象工厂模式(abstract factory)

    定义: 提供一个创建一系列相关或相互依赖对象的接口,而无需指定他们具体的类. 结构:(书中图,侵删) 这个图相对来说有一点点复杂,其实就是在工厂方法模式的基础上做了一些扩展,工厂方法模式只用于生成一种 ...

  9. lambda表达式 匿名函数

    lambda函数是一种快速定义单行最小函数的方法,是从Lisp借鉴而来的,可以用在任何需要函数的地方. 基础 lambda语句中,冒号前是参数,可以有多个,用逗号分割:冒号右边是返回值. lambda ...

  10. js 提交表单添加csrf

    function post(path, shipmentMap, method) { method = method || "post"; // Set method to pos ...