博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Python函数(九)-装饰器(二)
阅读量:2258 次
发布时间:2019-05-09

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

如果给被装饰器装饰的函数传递参数的话,需要在装饰器里修改

# -*- coding:utf-8 -*-__author__ = "MuT6 Sch01aR"import timedef timer(func):    def deco(n): #需要在此处设置形参        start_time = time.time()        func(n)        stop_time = time.time()        print("the run time is %s"%(stop_time-start_time))    return deco@timerdef test1(name):    time.sleep(3)    print('My name is %s'%name)test1('John')

运行结果

但是有两个或者多个被装饰的函数需要传递参数的话,这种情况就不太方便了

所以可以直接用*args和**kwargs,不管被装饰的函数有几个,传递的参数有多少,不管是什么类型的参数

# -*- coding:utf-8 -*-__author__ = "MuT6 Sch01aR"import timedef timer(func):    def deco(*args,**kwargs): #需要在此处设置形参        start_time = time.time()        func(*args,**kwargs)        stop_time = time.time()        print("the run time is %s"%(stop_time-start_time))    return deco@timerdef test1(name,age):    time.sleep(3)    print('My name is %s and my age is %s'%(name,age))@timerdef test2(name,language,city):    time.sleep(1)    print('%s is studying %s in %s'%(name,language,city))test1('John',22)test2('Jack',city='beijing',language='Chinese')

运行结果

 

转载于:https://www.cnblogs.com/sch01ar/p/8401815.html

你可能感兴趣的文章
Mysql系列七:分库分表技术难题之分布式全局唯一id解决方案
查看>>
【插件】jQuery.iviewer----图片浏览(滚动放大缩小问题解决)
查看>>
LayUi前端框架删除数据缓存问题(解决删除后刷新页面内容又会显示问题)
查看>>
基于FastJson的通用泛型解决方案
查看>>
WebSocket客户端连接不上和掉线的问题以及解决方案
查看>>
flask from app import db ImportError: cannot import name ‘db’ 的解决方案
查看>>
解决 IntelliJ IDEA Tomcat 控制台中文输出乱码问题
查看>>
解决php获取不到Authorization问题
查看>>
***小程序wx.getUserInfo不能弹出授权窗口后的解决方案
查看>>
Eclipse一直building workspace问题解决
查看>>
eclipse中生成的html存在中文乱码问题的解决方法
查看>>
Navicat Premium 12连接Oracle时提示oracle library is not loaded的问题解决
查看>>
Python selenium巧用Javascript脚本注入解决按钮点选问题
查看>>
高并发下接口幂等性解决方案
查看>>
adb devices 找不到设备的解决方法,亲测,超管用
查看>>
Failed to load resource: net::ERR_INSECURE_RESPONSE 问题解决记录
查看>>
element el-input 自动获取焦点和IE下光标位置解决方法
查看>>
Docker系列5--一些问题及解决
查看>>
微信支付 统一下单 字段 body 为中文时 报【签名错误】解决方案(C# SDK)
查看>>
关于antd Select 限制选择个数的解决方案
查看>>