解释Python装饰器的工作原理

解释Python装饰器的工作原理,第1张

解释Python装饰器的工作原理

装饰器是在Python中应用高阶函数的语法糖。高阶函数是将一个或多个函数作为输入并返回一个函数的函数。即

h(x) = f(g(x))

这里

f()
是一个高阶函数,它接受单个参数
g(x)
的函数,并返回单个参数的函数
h(x)
。您可以将其
f()
视为修改的行为
g()

高阶函数是可组合的(根据定义),因此在您的特定示例中,装饰器语法,

@helloGalaxy@helloSolarSystemdef hello(targetName=None):    ...

等价于

hello = helloGalaxy(helloSolarSystem(hello))

通过将代

hello
helloSolarSystem
,然后将其代入
helloGalaxy
,我们得到等效的函数调用,

def hello(targetName=None):    if targetName:      |     print("Hello, " + targetName + "!")   |  (1)  |    else:    |       |  (2)   |        print("Hello, world!")     |       |        |  (3)    print("Hello, solar system!")          |        |    print("Hello, galaxy!")   |

其中(1)是原件的应用

hello()
,(2)是原件的应用,

def helloSolarSystem(original_function):    def new_function(*args, **kwargs):        original_function(*args, **kwargs)   <-- (1)        print("Hello, solar system!")    return new_function

(3)是的应用,

def helloGalaxy(original_function):    def new_function(*args, **kwargs):        original_function(*args, **kwargs)   <-- (2)        print("Hello, galaxy!")    return new_function


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5666730.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存