python基础——装饰器
来源:互联网 发布:ks线切割编程系统 编辑:程序博客网 时间:2024/06/06 20:24
装饰器:本质是函数,(装饰其他函数)就是为其他函数添加附加功能。
装饰器用途:在不修改原函数源代码和调用方式的情况下,为原函数添加新的功能。
原则:1.不能修改被装饰的函数的源代码
2.不能修改被装饰的函数的调用方式
高阶函数+嵌套函数=》装饰器
举例
这种不能传递参数,不是通用型,通俗的说就是在函数外套一个函数,把原函数当做参数传递进去,并在里头调用加上要实现的功能,最后返回内层函数的地址。
import time#装饰器def timer(func):#外层函数,func是形参,把原函数的地址传递进来 def deco(): start_time=time.time()#实现的新功能 func()#地址加了括号就是调用,即调用原函数 stop_time=time.time()#实现的新功能 print("the func run time is ,(stop_time-start_time))"#实现的新功能 return deco#返回内层函数的地址@timer #test1=timer(test1),必须要有这个,这个其实就是test1=decodef test1(): time.sleep(3) print("int the test1")test1()#test1()=deco(),做了一个转换,之所以这样做的原因是deco()不能直接用,它是一个局部函数
通用型,可以传递任意个参数,应用场景:有些函数需要添加相同的功能,但是它们当中有些需要传递参数进去(不同的原函数有不同的功能,但它们添加的新功能相同),有些不需要,这个时候就需要实现能兼容传递参数和不传递参数的装饰器,下面的例子就是这样的一个通用型装饰器。
import timedef timer(func): def deco(*args,**kwargs):#注意这里需要传递参数 start_time=time.time() func(*args,**kwargs)#注意这里需要传递参数 stop_time=time.time() print("the total time is:",(stop_time-start_time)) return deco@timer# @timer要紧挨着被装饰函数的上方def test1(): time.sleep(3) print("int the test1")@timerdef test2(name,age):#这个原函数需要传递参数 time.sleep(3) print("test2:",name,age)test1()test2("Jorocco",23)
这种情况是装饰器带有参数,当我们的外层函数有参数的时候,此时需要在外面再加一层
import timeuser,passwd="Jorocco","123ab"def auth(auth_type): def outer_wrapper(func): def wrapper(*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)#1号位置,有返回值,就需要有这个 print("---after authenticaion") return res#1号位置,有返回值,就需要有这个,不然就没有1号位置的返回结果 else: exit("\033[31;1mInvalid usrname or password\033[0m") elif auth_type=="ldap": print("gameover") return wrapper return outer_wrapperdef index(): print("welcome to index")@auth(auth_type="local")#auth_type="local"有这个参数def home(): print("welcome to home") return 3# 1号位置,有返回值@auth(auth_type="ldap")def bbs(): print("welcome to bbs")index()print(home())bbs()
阅读全文
0 0
- Python——装饰器基础
- python基础——装饰器
- python基础——装饰器
- python基础----装饰器
- Python 装饰器基础
- python—装饰器
- python—装饰器
- Python 基础 —— 装饰器(1)
- Python 基础 —— 装饰器(2)
- python基础(06)——装饰器
- python基础—(高阶,匿名,偏)函数 | 装饰器
- Python基础17--装饰器
- Python基础:13装饰器
- python基础篇--装饰器
- python基础---装饰器模式
- python基础学习-装饰器
- python基础-装饰器进阶
- Python基础-装饰器-Decorator
- zookeeper简介
- Tab选项卡切换
- 获取客户端的真实IP地址
- 最近公共祖先(LCA)问题 笔记
- B树和B+树
- python基础——装饰器
- 杂记android
- 通过Nvram读取WIFI MAC地址
- Windows下配置Git服务器和客户端及初始使用
- Node.js 中间层 遍历请求接口遇到的问题
- nodeJs常用util工具函数
- 机器学习-softmax逻辑回归源码实现
- 6008
- webpack的基本配置项详解