博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
装饰器
阅读量:7229 次
发布时间:2019-06-29

本文共 890 字,大约阅读时间需要 2 分钟。

# -*- coding:utf-8 -*- def outer(func):    def inner():        print("hello")        r=func()        print("byebye")        return r    return inner@outerdef f1():    print("lvjy")f1()#@的作用:#1.执行outer函数,并且将其下面的函数名当作参数#2.将outer的返回值重新赋值给f1=outer的返回值 #@符号等价于f2=outer(f1) f2()

 

原函数带参数:

def decorator(func):    def inner(a,b):        print("before add")        ret=func(a,b)        print('a+b=',ret)        print("after add")        return ret    return inner@decoratordef add(a,b):    return a+badd(1,2)

装饰器可以接收任意个参数

def decorator(func):    def inner(*args,**kwargs):        print("before operation")        ret=func(*args,**kwargs)        print(ret)        print("after operation")        return ret    return inner@decoratordef add(a,b):    return a+b@decoratordef double(a):    return 2*aadd(1,2)double(4)

多个装饰器装饰同一个函数:

 

装饰器的应用:在登录时进行用户的权限认证

 

转载于:https://www.cnblogs.com/lvjygogo/p/8527318.html

你可能感兴趣的文章
vue中父组件给子组件额外添加参数
查看>>
分片上传
查看>>
网络编程初识和socket套接字
查看>>
什么是构造函数?它和普通函数的区别?
查看>>
mysql中key 、primary key 、unique key 与index区别
查看>>
zabbix使用企业微信发送告警信息
查看>>
zabbix4.0离线快速编译安装(编译安装方法)
查看>>
[Java开发之路](7)RandomAccessFile类详解
查看>>
Linux中的tty与pts
查看>>
Java socket示例(demo)TCP/IP
查看>>
error: WatchKit App doesn't contain any WatchKit Extensions whose WKAppBundleIdentifier matches
查看>>
计算UITextView的滑动高度
查看>>
AngularJs的UI组件ui-Bootstrap分享(四)——Datepicker Popup
查看>>
Java虚拟机------垃圾收集器
查看>>
UVA 1376 Animal Run 最短路
查看>>
oracle12c之 单机12.1.0.1打补丁
查看>>
封装了集中常用的文件读的方法
查看>>
51Nod-1080 两个数的平方和【暴力法】
查看>>
Web开发实用网站资源
查看>>
“深入理解”—交换排序算法
查看>>