小编典典

解释Python装饰器的工作原理

python

这是python装饰器的示例。我无法理解它的工作方式。请向我解释给定示例的控制流程。我将非常有义务。

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

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

@helloGalaxy
@helloSolarSystem
def hello(targetName=None):
     if targetName:
        print("Hello, " +  targetName +"!")
     else:
        print("Hello, world!")
hello("Earth")

阅读 153

收藏
2020-12-20

共1个答案

小编典典

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

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

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

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

@helloGalaxy
@helloSolarSystem
def hello(targetName=None):
    ...

等价于

hello = helloGalaxy(helloSolarSystem(hello))

通过将代hellohelloSolarSystem,然后将其代入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
2020-12-20