装饰器

定义:本质是函数,为其他函数添加附加的功能。

原则: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/语法糖的更多相关文章

  1. python中装饰器(语法糖)概念

    “”“” 什么是装饰器? """ 还是通过一个例子来慢慢说明 先看下面的例子 def func_1(x): return x*2 def fun_2(x): return ...

  2. Python学习---装饰器/迭代器/生成器的学习【all】

    Python学习---装饰器的学习1210 Python学习---生成器的学习1210 Python学习---迭代器学习1210

  3. day13 装饰器与语法糖

    day13 装饰器与语法糖 一.装饰器 1.什么是装饰器 装饰器就是装饰别人的工具,具体是指为被装饰者添加新功能 装饰器->函数 被装饰者->函数 2.为何要用装饰器 装饰器的核心思想:( ...

  4. 详解python的装饰器decorator

    装饰器本质上是一个python函数,它可以让其它函数在不需要任何代码改动的情况下增加额外的功能. 装饰器的返回值也是一个函数对象.它经常用于有切面需求的场景,比如:插入日志,性能测试,事务处理,缓存, ...

  5. python函数编程-装饰器decorator

    函数是个对象,并且可以赋值给一个变量,通过变量也能调用该函数: >>> def now(): ... print('2017-12-28') ... >>> l = ...

  6. Python学习---装饰器的学习1210

    装饰器的基础 学习前提: 作用域 + 函数的理解 + 闭包  [学习,理解] 代码编写原则: 对修改开放对扩展开放 装饰器本质上是一个函数,该函数用来处理其他函数,它可以让其他函数在不需要修改代码的前 ...

  7. Python基础之函数:2、globlal与nonlocal和闭包函数、装饰器、语法糖

    目录 一.global与nonlocal 1.global 2.nonlocal 二.函数名的多种用法 三.闭包函数 1.什么是闭包函数 2.闭包函数需满足的条件 3.闭包函数的作用 4.闭包函数的实 ...

  8. python学习---装饰器

    什么是装饰器 器即函数 装饰即修饰,意指为其他函数添加新功能 装饰器定义:本质就是函数,功能是为其他函数添加新功能 装饰器需要遵循的原则 1.不修改被装饰函数的源代码(开放封闭原则) 2.为被装饰函数 ...

  9. python_装饰器_语法糖

    什么是高阶函数? -- 把函数名当做参数传给另外一个函数,在另外一个函数中通过参数调用执行 #!/usr/bin/python3 __author__ = 'beimenchuixue' __blog ...

随机推荐

  1. 1-7SpringBoot之表单验证@Valid

    SpringBoot提供了强大的表单验证功能实现,给我们省去了写验证的麻烦: 这里我们给下实例,提交一个有姓名和年龄的表单添加功能, 要求姓名不能为空,年龄必须是不小于18 : 我们先新建一个Stud ...

  2. 201706 Ruby 基础 & 元编程

    yield yield self Proc yield带参数 rails中:yield 和 content_for methods.proc.lambda.block 闭包(用proc延长变量的生命周 ...

  3. esxi 版本升级命令

    先把zip文件通过XShell或者WinSCP上传到esxi服务器上面去,然后执行以下命令,完成升级并重启就可以了.

  4. JS动态判断设备类型为PC或者移动端,然后根据设备加载相应的代码

    这里是通过JS判断设备之后加载相应的网站,如果是移动端加载m开头的网站域名,如果是PC端就加载 www.开头的正式域名 <script> (function () { var url = ...

  5. php截取指定两个字符之间的字符串

    //截取指定两个字符之间的字符串 public function cut($begin,$end,$str){ $b = mb_strpos($str,$begin) + mb_strlen($beg ...

  6. 微信小程序-发送模板消息

    1 添加一个小程序的消息模板,获取到模板id,存储到数据库中,方便以后修改调用 2. https://developers.weixin.qq.com/miniprogram/dev/api-back ...

  7. 007.Oracle数据库 , 使用%进行模糊查询

    /*Oracle数据库查询日期在两者之间*/ SELECT PKID, OCCUR_DATE, ATA FROM LM_FAULT WHERE ( ( OCCUR_DATE >= to_date ...

  8. 比较 CEILING 和 FLOOR

    CEILING 函数返回大于或等于所给数字表达式的最小整数. FLOOR 函数返回小于或等于所给数字表达式的最大整数. 例如,对于数字表达式  12.9273,CEILING 将返回 13,FLOOR ...

  9. Oracle自动备份bat

    很多时候我们需要自动备份数据库这边推荐bat+Windows计划任务实现 方案1 创建以下bat 然后添加到TaskSchedule(路径最好不要包含中文) @echo off @echo ===== ...

  10. Oracle 建库

    Oracle得安装就不多说了 不过还是建议直接去官网下  其他渠道可能会导致安装问题  具体自己慢慢体会吧  !  下面主要说下怎么用Oracle建库并且建用户角色 Database configur ...