解释Python装饰器的工作方式 [英] Explain how Python decorator works

查看:85
本文介绍了解释Python装饰器的工作方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

This is an example for python decorator. I am unable to understand the way it works. Please explain me the given example's control flow. I will be highly obliged.

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")


推荐答案

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

Decorators are syntactic sugar for applying higher-order functions in Python. A higher-order function is a function that takes one or more functions as inputs and returns a function. i.e.

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

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

where here f() is a higher-order function that takes a function of a single argument, g(x), and returns a function of a single argument, h(x). You can think of f() as modifying the behaviour of g().

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

Higher-order functions are composable (by definition), so in your specific example, the decorator syntax,

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

等于,

hello = helloGalaxy(helloSolarSystem(hello))

通过将 hello 替换为 helloSolarSystem ,然后将其结果替换为 helloGalaxy ,我们得到等效的函数调用,

By substituting hello into helloSolarSystem, then the result of that into helloGalaxy, we get the equivalent function call,

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)是应用程序,

where (1) is the application of the original hello(), (2) is the application of,

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

并且(3)是以下应用,

and (3) is the application of,

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

这篇关于解释Python装饰器的工作方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆