打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
python学习之装饰器的理解和使用

装饰器是学习Python中非常重要的知识点,也是会让许多初学者容易迷惑的内容。下面从初学者的角度,加强装饰器的理解和使用。

装饰器使用的标识符号是@,常常会在代码中看到这个符号,但却是容易让初学者迷惑的一行代码。下面就举两个例子,帮助初学者理解什么是装饰器。

(1)简单装饰器

def decorator_simple(func): def outer(): print('This is outer function.') func() return outer()@decorator_simpledef inner(): print('This is inner function.')

输出结果为:

代码理解:这个例子是inner函数是没有任何参数的,装饰器部分的内容相当于inner=decorator_simple(inner),即将inner函数作为参数调用,即实现了内部函数,同时对内部函数装饰,增加了相应的功能,最后返回给inner函数,这样就实现了装饰函数decorator_simple对inner的装饰功能,当然decorator_simple也可以对其他函数进行装饰,提高了代码的复用程度,保持代码的简洁。上述代码相当于如下的代码。

def decorator_simple(func):    def outer():        print('This is outer function.')        func()    return outer()def inner():    print('This is inner function.')inner = decorator_simple(inner)

(2)带参数的装饰器

def decorator_args(func): def outer(*args, **kwargs): print('This is the outer decorator') func(*args, **kwargs) return outer@decorator_argsdef inner(language, level): print('This is the inner function.') print('%s is %s' %(language, level))inner('python', 'No.1')

输出结果:

代码理解:这个例子跟上个例子不一样,inner(language,level)函数中是有两个参数,而在装饰器中的*args和**kwargs表示可以支持任意数量和类型的参数的输入,传导到decorator_args装饰函数中的子函数outer中。

最后,给初学者初学者建议的是,在阅读装饰器代码时可以转换成如下形式理解:

函数=装饰器(函数)

即通过装饰器,对函数添加功能,如对函数添加日志打印,对函数进行执行时间的统计和执行次数的控制等等。

如果加深了装饰器的理解后,还可以对类增加装饰器和实现自定义参数的装饰器等高级功能。

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
Python装饰器decorator用法实例
一文看懂Python系列之装饰器(decorator)(工作面试必读)
浅谈Python装饰器
python中 functools模块 闭包的两个好朋友partial偏函数和wraps包裹
给妹子讲python-S01E22神奇的装饰器
「Python小脚本」基于装饰器的函数日志脚本
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服