ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

Python装饰器

2023-08-03 17:44:38  阅读:321  来源: 互联网

标签:Python 编程  函数


Python是一种解释式、面向对象的高级编程语言。

装饰器是允许用户在不改变其结构的情况下向现有对象添加新功能的功能。

先决条件

  1. 对python函数的基本理解。
  2. **args和**kwargs

Python函数被定义为头等舱对象。这意味着python函数可以分配给变量,将它们作为参数传递给其他函数,嵌套在其他函数中,并在其他函数中作为值返回它们。

为了很好地掌握python装饰器,我们将首先深入了解这个作为一流对象的功能概念。

1.为变量分配函数

在这里,我们将通过创建一个用“Hello World”消息问候用户的函数来演示这个概念。

def greet():
    return "Hello World"
message = greet
print(message())

上述代码的输出是Hello World

2.将函数作为参数传递

我们将通过创建两个功能来说明。greet函数将返回字符串Hello World,调用函数将接受函数作为参数,然后返回参数。

def greet():
    return "Hello World"

def call_function(function):
    return function()

print(call_function(greet))

上述代码的输出是Hello World

3.嵌套一个函数

Python还允许嵌套函数。这个概念在装饰师中至关重要。

def main():
    def greet():
        return "Hello World"
    return greet()

print(main())

如果上述函数是输出Hello World

4.在其他函数中返回函数

一个函数也可以由另一个函数生成。

def main():
    def say_hello():
        return "Hello"
    return say_hello
main_func = main()
print(main_func())

输出是Hello

创建装饰师

在经历了作为一流对象的函数概念后,我们现在将创建第一个装饰器。python装饰器与嵌套函数非常相似。为此,我们将创建两个函数,一个内部函数和一个外部函数,其中内部函数嵌套在外部函数内。

def make_lowercase(function):
    def wrapper():
        func = function()
        return func.lower()
    return wrapper

我们可以清楚地看到,我们的装饰器将函数作为参数。我们现在将创建一个函数,并将其传递给我们的装饰函数。

def say_hello():
    return "HELLO WORLD"

decorator = make_lowercase(say_hello)
print(decorator())

输出是hello world

Python还提供了另一种将装饰器分配给函数的方法。我们可以使用@符号后跟装饰师的名字。

@make_lowercase
def say_hello():
    return "HELLO WORLD"

print(say_hello())

输出是Hello World

使用多个装饰器

我们还可以在python函数中应用多个装饰器。例如,假设我们还想把函数的执行延迟5秒。然后,我们将定义一个用于延迟函数执行的装饰器函数,如下所示。

import time
def delay(function):
    def wrapper():
        time.sleep(5)
        return function()
    return wrapper
@delay()
@make_lowercase
def say_hello():
    return "HELLO WORLD"

print(say_hello())

输出仍然是Hello World,但函数say_hello的执行延迟了5秒。

用参数定义装饰函数

我们还可以定义一个接受参数的装饰器函数。我们将通过在包装函数中定义参数来做到这一点,其中这些参数将传递给运行时被装饰的函数。

def make_title(function):
    def wrapper(arg1):
        function(arg1.title())
    return wrapper

@make_title
def book(title):
    print(f"The title of the book is {title}")

book("broken glass")

上述片段的输出是The title of the book is Broken Glass,其中参数python是标题格式。

带有*args和**kwargs的装饰器功能

我们可以定义一个接受*args和**kwargs的装饰器函数。*args存储所有位置参数,**kwargs存储所有关键字参数。

def decorate(function):
    def wrapper(*args, **kwargs):
        print(f"The args are {args}")
        print(f"The kwargs are {kwargs}")
        function(*args, **kwargs)
    return wrapper

@decorate
def function_with_no_arguments():
    print("Has no arguments")

function_with_no_arguments()

我们定义了一个装饰器,它接受参数并将参数传递给装饰函数。我们还定义了一个名为function_with_no_arguments的函数,该函数不接受任何参数,并用装饰器函数装饰它。函数的输出是

The args are ()
The kwargs are {}
Has no arguments

现在让我们用位置参数来装饰一个函数。

@decorate
def function_with_arguments(arg1, arg2):
    print("This function has arguments")

function_with_arguments("Python", "Java")

function_with_arguments的输出是:

The args are ('Python', 'Java')
The kwargs are {}
This function has arguments

我们可以看到args Python和Java被打印到控制台。

让我们看看带有关键字参数的函数会是什么样子。

@decorate
def function_with_kwargs(**kwargs):
    print("Has kwargs")

function_with_kwargs(car="Subaru", model="SUBARU CROSSTREK SUV 2021")

function_with_arguments的输出是:

The args are ()
The kwargs are {'car': 'Subaru', 'model': 'SUBARU CROSSTREK SUV 2021'}
Has kwargs

我们可以看到args Python和Java被打印到控制台。

标签:Python,编程, 函数
来源:

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有