本文实例讲述了Python装饰器用法。分享给大家供大家参考,具体如下:
无参数的装饰器
#coding=utf-8 def log(func): def wrapper(): print 'before calling ',func.__name__ func() print 'end calling ',func.__name__ return wrapper @log def hello(): print 'hello' @log def hello2(name): print 'hello',name if __name__=='__main__': hello()
运行结果:
before calling hello
hello
end calling hello
带参数的装饰器:
#coding=utf-8 def log(func): def wrapper(name): print 'before calling ',func.__name__ func(name) print 'end calling ',func.__name__ return wrapper @log def hello(name): print 'hello',name @log def hello2(name): print 'hello',name if __name__=='__main__': hello('haha')
运行结果:
before calling hello
hello haha
end calling hello
多个参数的时候:
#coding=utf-8 def log(func): ''' *无名字的参数 **有名字的参数 :param func: :return: ''' def wrapper(*args,**kvargs): print 'before calling ',func.__name__ print 'args',args,'kvargs',kvargs func(*args,**kvargs) print 'end calling ',func.__name__ return wrapper @log def hello(name,age): print 'hello',name,age @log def hello2(name): print 'hello',name if __name__=='__main__': hello('haha',2) hello(name='hehe',age=3)
输出:
end calling hello
before calling hello
args () kvargs {'age': 3, 'name': 'hehe'}
hello hehe 3
end calling hello
装饰器里带参数的情况
本质就是嵌套函数
#coding=utf-8 def log(level,*args,**kvargs): def inner(func): def wrapper(*args,**kvargs): print level,'before calling ',func.__name__ print level,'args',args,'kvargs',kvargs func(*args,**kvargs) print level,'end calling ',func.__name__ return wrapper return inner @log(level='INFO') def hello(name,age): print 'hello',name,age @log def hello2(name): print 'hello',name if __name__=='__main__': hello('haha',2)
运行输出:
INFO before calling hello
INFO args ('haha', 2) kvargs {}
hello haha 2
INFO end calling hello
更多关于Python相关内容可查看本站专题:《Python数据结构与算法教程》、《Python Socket编程技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程》
希望本文所述对大家Python程序设计有所帮助。
Python,装饰器
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
RTX 5090要首发 性能要翻倍!三星展示GDDR7显存
三星在GTC上展示了专为下一代游戏GPU设计的GDDR7内存。
首次推出的GDDR7内存模块密度为16GB,每个模块容量为2GB。其速度预设为32 Gbps(PAM3),但也可以降至28 Gbps,以提高产量和初始阶段的整体性能和成本效益。
据三星表示,GDDR7内存的能效将提高20%,同时工作电压仅为1.1V,低于标准的1.2V。通过采用更新的封装材料和优化的电路设计,使得在高速运行时的发热量降低,GDDR7的热阻比GDDR6降低了70%。