一、装饰器含义

  装饰器本质就是函数,为其它函数添加附加功能

二、装饰器原则

  1.不修改被修饰函数的代码

  2.不修改被修饰函数的调用方式

三、装饰器知识

  装饰器 = 高阶函数 + 函数嵌套 + 闭包

四、装饰器介绍

  1.装饰器基本框架
def timer(func):    #func为被修饰函数
def wrapper(): #函数嵌套
func() #执行func函数
return wrapper
  2、基本装饰器(基本框架+参数+功能+返回值+使用装饰器+语法糖@)
import time

def timmer(func): #func=test
def wrapper():
# print(func)
start_time=time.time()
func() #就是在运行test()
stop_time = time.time()
print('运行时间是%s' %(stop_time-start_time))
return wrapper @timmer #test=timmer(test) timmer执行后会返回wrapper地址赋值给test
def test():
time.sleep(3)
print('test函数运行完毕') test()
  3.加上返回值的装饰器
import time

def timmer(func): #func=test
def wrapper():
# print(func)
start_time=time.time()
res = func() #就是在运行test()
stop_time = time.time()
print('运行时间是%s' %(stop_time-start_time))
return res
return wrapper @timmer #test=timmer(test) timmer执行后会返回wrapper地址赋值给test
def test():
time.sleep(3)
print('test函数运行完毕')
return '这是test的返回值' res2 = test()
print (res2) 输出:
test函数运行完毕
运行时间是3.0001718997955322
这是test的返回值
  4.加上参数的装饰器
import time
def timmer(func): #func=test1
def wrapper(*args,**kwargs): #test('linhaifeng',age=18) args=('linhaifeng') kwargs={'age':18}
start_time=time.time()
res=func(*args,**kwargs) #就是在运行test() func(*('linhaifeng'),**{'age':18})
stop_time = time.time()
print('运行时间是%s' %(stop_time-start_time))
return res
return wrapper # @timmer #test=timmer(test)
def test(name,age):
time.sleep(3)
print('test函数运行完毕,名字是【%s】 年龄是【%s】' %(name,age))
return '这是test的返回值' @timmer
def test1(name,age,gender):
time.sleep(1)
print('test1函数运行完毕,名字是【%s】 年龄是【%s】 性别【%s】' %(name,age,gender))
return '这是test的返回值' # res=test('linhaifeng',age=18) #就是在运行wrapper
# # print(res)
# test1('alex',18,'male') test1('alex',18,'male')
  5.带参数的装饰器
 1 user_list=[
2 {'name':'alex','passwd':''},
3 {'name':'linhaifeng','passwd':''},
4 {'name':'wupeiqi','passwd':''},
5 {'name':'yuanhao','passwd':''},
6 ]
7 current_dic={'username':None,'login':False}
8
9 def auth(auth_type='filedb'):
10 def auth_func(func):
11 def wrapper(*args,**kwargs):
12 print('认证类型是',auth_type)
13 if auth_type == 'filedb':
14 if current_dic['username'] and current_dic['login']:
15 res = func(*args, **kwargs)
16 return res
17 username=input('用户名:').strip()
18 passwd=input('密码:').strip()
19 for user_dic in user_list:
20 if username == user_dic['name'] and passwd == user_dic['passwd']:
21 current_dic['username']=username
22 current_dic['login']=True
23 res = func(*args, **kwargs)
24 return res
25 else:
26 print('用户名或者密码错误')
27 elif auth_type == 'ldap':
28 print('鬼才特么会玩')
29 res = func(*args, **kwargs)
30 return res
31 else:
32 print('鬼才知道你用的什么认证方式')
33 res = func(*args, **kwargs)
34 return res
35
36 return wrapper
37 return auth_func
38
39 @auth(auth_type='filedb') #auth_func=auth(auth_type='filedb')-->@auth_func 附加了一个auth_type --->index=auth_func(index)
40 def index():
41 print('欢迎来到京东主页')
42
43 @auth(auth_type='ldap')
44 def home(name):
45 print('欢迎回家%s' %name)
46 #
47 @auth(auth_type='sssssss')
48 def shopping_car(name):
49 print('%s的购物车里有[%s,%s,%s]' %(name,'奶茶','妹妹','娃娃'))
50
51 # print('before-->',current_dic)
52 # index()
53 # print('after--->',current_dic)
54 # home('产品经理')
55 shopping_car('产品经理')
def auth(n):
def myfunc(func):
def wrapper(*args,**kwargs):
if n=='':
return func(*args,**kwargs)
else:
print('can shu bu cun zai')
return wrapper
return myfunc
@auth('')
def index():
print('欢迎来到京东主页') index()

支持参数的装饰器

021--python装饰器的更多相关文章

  1. 关于python装饰器

    关于python装饰器,不是系统的介绍,只是说一下某些问题 1 首先了解变量作用于非常重要 2 其次要了解闭包 def logger(func): def inner(*args, **kwargs) ...

  2. python装饰器通俗易懂的解释!

    1.python装饰器 刚刚接触python的装饰器,简直懵逼了,直接不懂什么意思啊有木有,自己都忘了走了多少遍Debug,查了多少遍资料,猜有点点开始明白了.总结了一下解释得比较好的,通俗易懂的来说 ...

  3. Python 装饰器学习

    Python装饰器学习(九步入门)   这是在Python学习小组上介绍的内容,现学现卖.多练习是好的学习方式. 第一步:最简单的函数,准备附加额外功能 1 2 3 4 5 6 7 8 # -*- c ...

  4. python 装饰器修改调整函数参数

    简单记录一下利用python装饰器来调整函数的方法.现在有个需求:参数line范围为1-16,要求把9-16的范围转化为1-8,即9对应1,10对应2,...,16对应8. 下面是例子: def fo ...

  5. python 装饰器学习(decorator)

    最近看到有个装饰器的例子,没看懂, #!/usr/bin/python class decorator(object): def __init__(self,f): print "initi ...

  6. Python装饰器详解

    python中的装饰器是一个用得非常多的东西,我们可以把一些特定的方法.通用的方法写成一个个装饰器,这就为调用这些方法提供一个非常大的便利,如此提高我们代码的可读性以及简洁性,以及可扩展性. 在学习p ...

  7. 关于python装饰器(Decorators)最底层理解的一句话

    一个decorator只是一个带有一个函数作为参数并返回一个替换函数的闭包. http://www.xxx.com/html/2016/pythonhexinbiancheng_0718/1044.h ...

  8. Python装饰器由浅入深

    装饰器的功能在很多语言中都有,名字也不尽相同,其实它体现的是一种设计模式,强调的是开放封闭原则,更多的用于后期功能升级而不是编写新的代码.装饰器不光能装饰函数,也能装饰其他的对象,比如类,但通常,我们 ...

  9. Python装饰器与面向切面编程

    今天来讨论一下装饰器.装饰器是一个很著名的设计模式,经常被用于有切面需求的场景,较为经典的有插入日志.性能测试.事务处理等.装饰器是解决这类问题的绝佳设计,有了装饰器,我们就可以抽离出大量函数中与函数 ...

  10. python装饰器方法

    前几天向几位新同事介绍项目,被问起了@login_required的实现,我说这是django框架提供的装饰器方法,验证用户是否登录,只要这样用就行了,因为自己不熟,并没有做过多解释. 今天查看dja ...

随机推荐

  1. 解密优秀博士成长史 ——微软亚洲研究院首届博士生学术论坛Panel讨论经验总结

    编者按:有人说“一入博门深似海”,读博前应该做好哪些准备?作为一名博士生,应该有怎样的学术或职业规划?导师还是老板?怎样在师生关系上做到双赢?你是导师心目中优秀的博士生吗?相信以上问题在很多同学心中萦 ...

  2. 创建es索引-格式化和非格式化

    创建es索引-格式化和非格式化 学习了:https://www.imooc.com/video/15768 索引有结构化和非结构化的区分: 1, 先创建索引,然后POST修改mapping 首先创建索 ...

  3. centos 7 -- Disk Requirements: At least 134MB more space needed on the / filesystem.

    用了幾年的centos7,今天執行yum update時,彈出一行有錯誤的提示:Disk Requirements:   At least 134MB more space needed on the ...

  4. [Javascript] Use a custom sort function on an Array in Javascript

    Sorting in Javascript with sort uses lexical sorting by default, which means it will sort in alphabe ...

  5. JVM 调优 —— 新生代 Survivor 空间不足

    零. 新生代调优规律 增大新生代空间. Minor GC 频率降低, Minor GC 时间上升. 降低新生代空间, Minor GC 频率上升, Minor GC 时间下降 一. 新生代典型问题 先 ...

  6. codeforces 553 A Kyoya and Colored Balls

    这个题.比赛的时候一直在往dp的方向想,可是总有一个组合数学的部分没办法求, 纯粹组合数学撸,也想不到办法-- 事实上,非常显然.. 从后往前推,把第k种颜色放在最后一个,剩下的k球.还有C(剩余的位 ...

  7. invlpg 指令简单介绍

    invlpg 指令简单介绍 void tlb_invalidate(pde_t *pgdir, void *va) { // Flush the entry only if we're modifyi ...

  8. Redis 脚本及其应用

    参考:http://www.runoob.com/redis/redis-scripting.html Redis 脚本使用 Lua 解释器来执行脚本. Reids 2.6 版本通过内嵌支持 Lua ...

  9. Linux查看IP 网关 DNS

    ifconfig查看IP: watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFC ...

  10. Express:模板引擎深入研究

    深入源码 首先,看下express模板默认配置. view:模板引擎模块,对应 require('./view'),结合 res.render(name) 更好了解些.下面会看下 view 模块. v ...