Python学习——装饰器/decorator/语法糖
装饰器
定义:本质是函数,为其他函数添加附加的功能。
原则:1、不能修改原函数的源代码
2、不能修改被原函数的调用方式
重点理解:
1、函数即“变量”
2、高阶函数:返回值中包含函数名
3、嵌套函数
高阶函数 + 嵌套函数 = 装饰器
热身: 先感受一下Python的解释器,结果可能和你预想的不同
__author__ = 'jcx' def foo():
print("in the foo")
bar() #解释器依次解释,先声明print后bar def bar():
print("in the bar") #找到bar,定义 foo() #只要在调用前声明就可以
Output:
in the foo
in the bar
应用:
1、通用版 打印程序执行时间
__author__ = 'jcx' import time def timer(func): #timer(test1) func = test1
def deco(*args, **kwargs): #这样写,就可以使被装饰的函数可以带参数
start_time = time.time()
func(*args, **kwargs)
stop_time = time.time()
print("Func RunTime = %s" % (stop_time - start_time))
return deco @timer #等于作了这部赋值 test1 = timer(test1)
def test1():
time.sleep(0.1)
print("in the test1") @timer
def test2(name,age): #test2 = timer(test2) test2() = deco()
print("test2:", name,age) test1() #实际是在执行deco()
test2("jcx",24) #带参数
24
输出结果:
in the test1
Func RunTime = 0.10228705406188965
test2: jcx 24
Func RunTime = 2.09808349609375e-05
2、多种方式登录网页/语法糖/嵌套
__author__ = 'jcx' import time
user,passwd = 'jcx', 'jcx123' def auth(auth_type):
print("auth type: ", auth_type)
def outer_wrapper(func):
def wrapper(*args, **kwargs):
# print("wrapper func: ", *args,**kwargs)
if auth_type == "local":
username = input("Username:".strip())
password = input("Password:".strip())
if user == username and passwd == password:
print("\033[32;1mUser has passed authentication\033[0m")
res = func(*args, **kwargs) #from home
print('-------->after authentication ')
return res
else:
exit("wrong username or password.")
elif auth_type == "ldap":
print('waiting...')
return wrapper
return outer_wrapper @auth
def index():
print("Welcome to index page") @auth(auth_type = "local") # home = auth() wrapper() 通过本地方式登录
def home():
print("Welcome to home page")
return "from home page" @auth(auth_type = "ldap") #通过ldap方式登录
def bbs():
print("Welcome to bbs page") index("local")
home()
输出结果:
auth type: <function index at 0x10ae390e0>
auth type: local
auth type: ldap
Username:jcx
Password:jcx123
User has passed authentication
Welcome to home page
-------->after authentication
waiting...
Python学习——装饰器/decorator/语法糖的更多相关文章
- python中装饰器(语法糖)概念
“”“” 什么是装饰器? """ 还是通过一个例子来慢慢说明 先看下面的例子 def func_1(x): return x*2 def fun_2(x): return ...
- Python学习---装饰器/迭代器/生成器的学习【all】
Python学习---装饰器的学习1210 Python学习---生成器的学习1210 Python学习---迭代器学习1210
- day13 装饰器与语法糖
day13 装饰器与语法糖 一.装饰器 1.什么是装饰器 装饰器就是装饰别人的工具,具体是指为被装饰者添加新功能 装饰器->函数 被装饰者->函数 2.为何要用装饰器 装饰器的核心思想:( ...
- 详解python的装饰器decorator
装饰器本质上是一个python函数,它可以让其它函数在不需要任何代码改动的情况下增加额外的功能. 装饰器的返回值也是一个函数对象.它经常用于有切面需求的场景,比如:插入日志,性能测试,事务处理,缓存, ...
- python函数编程-装饰器decorator
函数是个对象,并且可以赋值给一个变量,通过变量也能调用该函数: >>> def now(): ... print('2017-12-28') ... >>> l = ...
- Python学习---装饰器的学习1210
装饰器的基础 学习前提: 作用域 + 函数的理解 + 闭包 [学习,理解] 代码编写原则: 对修改开放对扩展开放 装饰器本质上是一个函数,该函数用来处理其他函数,它可以让其他函数在不需要修改代码的前 ...
- Python基础之函数:2、globlal与nonlocal和闭包函数、装饰器、语法糖
目录 一.global与nonlocal 1.global 2.nonlocal 二.函数名的多种用法 三.闭包函数 1.什么是闭包函数 2.闭包函数需满足的条件 3.闭包函数的作用 4.闭包函数的实 ...
- python学习---装饰器
什么是装饰器 器即函数 装饰即修饰,意指为其他函数添加新功能 装饰器定义:本质就是函数,功能是为其他函数添加新功能 装饰器需要遵循的原则 1.不修改被装饰函数的源代码(开放封闭原则) 2.为被装饰函数 ...
- python_装饰器_语法糖
什么是高阶函数? -- 把函数名当做参数传给另外一个函数,在另外一个函数中通过参数调用执行 #!/usr/bin/python3 __author__ = 'beimenchuixue' __blog ...
随机推荐
- Unity3d fbx纹理不显示 原因
Unity3d 导入fbx文件后纹理不显示(3ds Max中显示正常) 原因: 1.纹理图片没有导入fbx同一文件夹中 2.纹理图片没有在fbx文件之前导入(现导入纹理图片,再导入fbx文件)
- C# 篇基础知识11——泛型和集合
.NET提供了一级功能强大的集合类,实现了多种不同类型的集合,可以根据实际用途选择恰当的集合类型. 除了数组 Array 类定义在System 命名空间中外,其他的集合类都定义在System.Coll ...
- ReadyBoost 的应用教程
一.什么是ReadyBoost 根据百度百科介绍,ReadyBoost是存在于Windows Vista中的一项新技术,在继Vista的下一代操作系统Windows 7中,同样包 含着这项技术,它利用 ...
- 四 Hibernate的一级缓存&事务管理及其配置
持久态对象: 自动更新数据库,原理是一级缓存. 缓存:是一种优化的方式,将数据存入内存,从缓存/内存中获取,不用通过存储源 Hibernate框架中提供了优化手段:缓存,抓取策略 Hibernate中 ...
- 二十三 NoSql&Redis及其安装
什么是Nosql not only sql , 不仅仅是sql,是一项全新的数据库理念,泛指非关系型的数据库. 为什么需要NoSql 解决以下问题: 1 High Performance 对数据库 ...
- Redis之datatype概述
Redis支持的数据类型 String List Set Sorted Set Hashes Bit array HyperLogLog Bina ...
- Linux学习《第五章用户文件权限管理》之补充学习
- Kubernetes 各版本镜像列表
以下镜像列表由 kubeadm v1.11.1 导出,若使用预下载镜像离线部署的方式部署,请使用 kubeadm v1.11.1 版本 导出各版本镜像列表: kubeadm config images ...
- webpack 命令 Module build failed (from ./node_modules/babel-loader/lib/index.js) 错误问题解决方案
在项目中运行的时候出现报错,错误为Module build failed (from ./node_modules/babel-loader/lib/index.js) 解决方案: 控制台输入 np ...
- 查看oracle单签session
转自 https://blog.csdn.net/alexsong123/article/details/51858092 怎样查看oracle当前的连接数呢?只需要用下面的SQL语句查询一下就可以了 ...