装饰器

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. pip list 和 pip freeze

    https://blog.csdn.net/vitaminc4/article/details/76576956 Pip’s documentation statespip     descripti ...

  2. 转:jquery的$(function(){})和$(document).ready(function(){}) 的区别

    原文链接:https://www.cnblogs.com/slyzly/articles/7809935.html [转载]jquery的$(function(){})和$(document).rea ...

  3. java常用工具所在的包

    org.apache.commons.lang3:1)StringUtils.isBlank org.springframework.util:1)ResourceUtils.getFile(&quo ...

  4. excel之导出

    1.Maven依赖的jar包 <dependency>     <groupId>org.apache.poi</groupId>     <artifact ...

  5. python server

    #!/usr/bin/env python #coding=utf-8 # modifyDate: 20120808 ~ 20120810 # 原作者为:bones7456, http://li2z. ...

  6. Scala笔记

    定义包 package com.runoob { class HelloWorld } 引用包 import java.awt.Color // 引入Color import java.awt._ / ...

  7. es中如何定位不合法搜索

    GET /test_index/test_type/_validate/query?explain{ "query": { "math": { "te ...

  8. 'react-scripts' is not recognized as an internal or external command

    React项目在执行npm start的时候报下面的错误: 解决办法:把项目目录中node_modules文件夹删掉,重新npm install一下,然后再执行npm start

  9. RN导航栏使用

    import PropTypes from 'prop-types'; import React, { Component } from 'react'; import { NavigatorIOS, ...

  10. Linux命令实例功能笔记

    ls命令 ls对文件mtime时间进行排序 降序: ls -lt |  grep '^-'    升序:   ls -ltr  |  grep '^-' seq命令 求1000以内所有偶数的和 ech ...