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 ...
随机推荐
- IntelliJ如何设置自动导包
idea 关于自动导包的设置 标签: idea 2016-09-30 18:10 400人阅读 评论(0) 收藏 举报 本文章已收录于: .embody{ padding:10px 10px 10px ...
- 基于PIL模块创建验证码图片
def get_valid_img(request): # 方式2:基于PIL模块创建验证码图片 from PIL import Image, ImageDraw, ImageFont from io ...
- 吴裕雄--天生自然JAVA数据库编程:使用JDBC连接ORACLE数据库
DROP TABLE person ; DROP SEQUENCE myseq ; CREATE SEQUENCE myseq ; CREATE TABLE person ( id INT PRIMA ...
- 容器STL
一.迭代器iterator 迭代器是容器的一种遍历方式,每种容器都定义了自己的迭代器类型 声明一个迭代器: 容器名称<数据类型>::iterator 迭代器名称 vector<int ...
- PCHMI工控组态开发视频教程
PCHMI是一款适合所有PLC工程师快速上手工控组态开发的控件 下面是视频教程链接 PCHMI工控组态 02-按钮的使用 PCHMI工控组态 03-数据显示器使用 PCHMI工控组态 04-标签控件的 ...
- Docker + Maven + Docker-compose
前言: docker:容器化管理 maven:支持docker-maven的插件,通过 mvn clean -Dmaven.test.skip package dockerfile:build 打包命 ...
- QT5安装
Windows+Qt5.3.1+VS2013安装教程 https://blog.csdn.net/two_ye/article/details/96109876 (已成功)windows下,VS201 ...
- 图形与动画在Android中的实现
public class MyView extends View{ Bitmap myBitmap; Paint paint; public MyView(Context context, Attri ...
- kali linux 添加源 及为firefox esr 添加 flash 插件 --2017
终端 输入 vim /etc/apt/sources.list 在文件内写入 #中科大deb http://mirrors.ustc.edu.cn/kali kali-rolling main non ...
- 055、Java中使用for循环输出乘法口诀表
01.代码如下: package TIANPAN; /** * 此处为文档注释 * * @author 田攀 微信382477247 */ public class TestDemo { public ...