python装饰器这件小事

什么是装饰器?
装饰器是一种高级函数,它能够在不修改原函数代码的情况下,扩展函数的功能。装饰器实际上是一个返回函数的函数。
基本语法

def my_decorator(func):#参数为传入一个函数
    def wrapper(*args, **kwargs): #函数名称可以随意调整,如inner
        # 代码在这里
        result = func(*args, **kwargs)#函数名称为外层函数传入的参数函数
        # 代码在这里
        return result
    return wrapper # 返回对象为函数名称

装饰器的使用
你可以使用 @decorator_name 语法将装饰器应用到函数上。

@my_decorator
def my_function():
    pass

你可以使用 @decorator_name 语法将装饰器应用到类上。

from django.utils.decorators import method_decorator

@method_decorator(mydecorators.wrapper,name='get')
# 对get函数加装饰器函数
class AddAuthor(View):

    def get(self,request):
        return render(request, 'add_author.html')

    def post(self,request):
        name = request.POST.get('name')
        bio = request.POST.get('bio')
        sql = f"INSERT INTO author(name,bio) VALUES('{name}','{bio}')"
        message = dbo.dbDdlData(sql)
        if message == "success":
            return redirect('/list_authors/')

示例 1:简单的装饰器
定义一个装饰器,它在函数调用前后打印消息。

def simple_decorator(func):
    def wrapper(*args, **kwargs):
        print("Before the function call")
        result = func(*args, **kwargs)
        print("After the function call")
        return result
    return wrapper

# 以函数为例,进行使用简单展示,相对输出简单,对类的使用需要参考上面的基本方法中的使用示例
@simple_decorator
def say_hello(name):
    print(f"Hello, {name}!")

say_hello("Alice")

输出:

Before the function call
Hello, Alice!
After the function call

示例 2:带参数的装饰器
如果需要让装饰器本身接受参数,可以再定义一层函数。

def repeat_decorator(times):#相对于无参装饰器函数,此次多了一层函数,用来接收参数
    def decorator(func):
        def wrapper(*args, **kwargs):
            for _ in range(times):
                result = func(*args, **kwargs)
            return result
        return wrapper
    return decorator

@repeat_decorator(times=3) #当装饰器需要接收参数时,需要带上括号并传入对应的参数
def greet(name):
    print(f"Hello, {name}!")

greet("Alice")

输出:

Hello, Alice!
Hello, Alice!
Hello, Alice!

示例 4:类装饰器
除了函数装饰器,你还可以使用类来实现装饰器。

class ClassDecorator:
    def __init__(self, func):
        self.func = func

    def __call__(self, *args, **kwargs):
        print("ClassDecorator before call")
        result = self.func(*args, **kwargs)
        print("ClassDecorator after call")
        return result

@ClassDecorator
def say_goodbye(name):
    print(f"Goodbye, {name}!")

say_goodbye("Alice")

输出:

ClassDecorator before call
Goodbye, Alice!
ClassDecorator after call

装饰器可以用来在不修改原函数代码的情况下添加功能。

posted @   克瑞斯  阅读(7)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示