Python装饰器(decorator)不过如此,是我想多了

Python装饰器是Python中一个非常有趣的特性,可以利用Python装饰器对一个函数包装再包装,其实从效果上看有一点像AOP中的切面,也就是对函数调用进行拦截,那么通过Python装饰器可以做哪些有趣的事情,以及Python装饰器的原理是什么呢?继续看本文吧!
defsay():return"Hello"print(say()))
<b><i>Hello</i></b>
def decorator(fun): # 装饰器中的代码
from functools import wrapsdefmakebold(fn):defmakebold_wrapped(*args, **kwargs):return"<b>" + fn(*args, **kwargs) + "</b>"return makebold_wrappeddefmakeitalic(fn):defmakeitalic_wrapped(*args, **kwargs):return"<i>" + fn(*args, **kwargs) + "</i>"return makeitalic_wrapped
defsay():return"Hello"print(say.__name__) # 输出函数名
makebold_wrapped
defshout(word="yes"):return word.capitalize()# 输出:Yesprint(shout())# 将shout函数赋给另一个变量,这里并没有使用圆括号,# 所以不是调用函数,而是将函数赋给另一个变量,也就是为函数起一个别名scream = shout# 可以用scream调用shout函数# 输出:Yesprint(scream())# 目前,同一个函数,有两个引用:scream和shout,可以使用del删除一个引用del shouttry:# 该引用删除后,就不能通过该引用调用函数了 print(shout())except NameError as e: print(e)# 仍然可以通过另外一个引用调用函数# 输出:Yesprint(scream())
deftalk():# 内嵌函数defwhisper(word="YES"):return word.lower()+"..."# 调用内嵌函数 print(whisper())# 调用talk,whisper函数在talk内部被调用# 输出:yes...talk()try:# 但whisper函数在talk函数外部并不可见,所以调用会哦抛出异常 print(whisper())except NameError as e: print(e)
defgetTalk(kind="shout"):# 定义第1个内嵌函数defshout(word="yes"):return word.capitalize()+"!"# 定义第2个内嵌函数defwhisper(word="yes") :return word.lower()+"..."# 根据参数值返回特定的函数if kind == "shout":# 这里没有使用一对圆括号,所以不是调用函数,而是返回函数本身return shoutelse:return whisper# talk是函数本身,并没有被调用talk = getTalk()# 输出函数本身# 输出:<function getTalk.<locals>.shout at 0x7f93a00475e0>print(talk)# 调用talk函数(其实是shout函数)print(talk())#outputs : Yes!# 调用whisper函数print(getTalk("whisper")())
def doSomethingBefore(func):print("I do something before then I call the function you gave me")print(func())doSomethingBefore(talk)
# 装饰器函数,参数是另一个函数(被装饰的函数)defmy_shiny_new_decorator(a_function_to_decorate):# 装饰器的内嵌函数,用来包装被修饰的函数defthe_wrapper_around_the_original_function():# 在调用被修饰函数之前输出一行文本 print("Before the function runs")# 调用被装饰函数 a_function_to_decorate()# 在调用被修饰函数之后输出一行文本 print("After the function runs")# 返回包装函数return the_wrapper_around_the_original_function# 这个函数将被my_shiny_new_decorator函数修饰defa_stand_alone_function(): print("I am a stand alone function, don't you dare modify me")# 调用函数a_stand_alone_function()# 修饰a_stand_alone_function函数a_stand_alone_function_decorated = my_shiny_new_decorator(a_stand_alone_function)a_stand_alone_function_decorated()
I am a stand alone function, don'tyoudaremodifymeBeforethefunctionrunsIamastandalonefunction, don'tyoudaremodifymeAfterthefunctionruns
defa_stand_alone_function(): print("I am a stand alone function, don't you dare modify me")
- EOF -
想深入学习Python的同学,可以识别上面二维码进入课程页面
惊喜不断,鸿蒙IDE全新升级,4大功能助力App开发!
这样合并Python字典,可以让程序的运行效率提高4倍
Python字典不是不可以排序,是你方法没用对!
文件侠告诉你,Python复制文件的N种姿势!
Python代码可以加密吗?Python字节码告诉你!
使出Python的六脉神剑,让Python拥有无限扩展性
看我用元类(metaclass)花式创建Python类
你不知道__name__变量是什么意思吗?
Python生成器(Generator)最完美解释
关注「极客起源」公众号,加星标,不错过精彩技术干货
本文分享自微信公众号 - 极客起源(geekculture)。
如有侵权,请联系 support@oschina.cn 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一起分享。
以上是 Python装饰器(decorator)不过如此,是我想多了 的全部内容, 来源链接: utcz.com/z/509498.html

