Python—8.1、装饰器

文档目录

  • 概念简介
  • 代码引用
    • 1、常规实现(函数无参,无返回值)
    • 2、
    • 装饰器形式(函数无参,无返回值)
    • 多个装饰器
    • 代参装饰器
  • 类装饰器

参考博客:https://blog.csdn.net/weixin_44992737/article/details/125868592

概念简介

python中的装饰器(decorator)一般采用语法糖的形式,是一种语法格式。比如:@classmethod、@staticmethod、@property、@xxx.setter、@wraps()、@func_name等都是python中的装饰器。
装饰器装饰的对象是函数或者方法,各种装饰器的作用都是一样的:改变被装饰函数或者方法的功能或性质。

正式定义:
装饰器本质上是一个Python函数(其实就是闭包),它可以让其他函数在不需要做任何代码变动的前提下增加额外功能,装饰器的返回值也是一个函数对象。装饰器用于以下场景,如插入日志、性能测试、事务处理、缓存、权限校验等场景。

代码引用

如在某些场景下希望记录某个函数的执行时间,在不改变函数的内容前提下;

1、常规实现(函数无参,无返回值)

# -*- coding= utf-8 -*-
"""
@DevTool  : PyCharm
@Author   : gzh
@DateTime : 2023/6/15 13:41
@FileName : appprog.py
"""
import threading
import time
import sys


def task_a():
    time.sleep(5)
    print("function:" + sys._getframe().f_code.co_name + " self sleep 5 seconds!")


def how_long_time(fun):
    def proxy_fun():
        start_time = time.time()
        fun()
        end_time = time.time()
        print("function-->{} runing {} seconds!".format(fun.__name__, end_time - start_time))

    return proxy_fun


if __name__ == "__main__":
    task_a = how_long_time(task_a)
    task_a()

结果输出:

function:task_a self sleep 5 seconds!
function-->task_a runing 5.011642932891846 seconds!

Process finished with exit code 0

2、

装饰器形式(函数无参,无返回值)

# 函数how_long_time定义和上面一致

@how_long_time
def task_a():
    time.sleep(5)
    print("function:" + sys._getframe().f_code.co_name + " self sleep 5 seconds!")


if __name__ == "__main__":
    task_a():

多个装饰器


def record_StepLog(fun):
    def proxy_fun():
        print("[tracker]:function-->{} is runing on first step!".format(fun.__name__))
        fun()
        print("[tracker]:function-->{} all steps runing completed!".format(fun.__name__))

    return proxy_fun

@record_StepLog
@how_long_time
def task_a():
    time.sleep(5)
    print("function:" + sys._getframe().f_code.co_name + " self sleep 5 seconds!")

if __name__ == "__main__":
    task_a()

输出结果:

[tracker]:function-->proxy_fun is runing on first step!
function:task_a self sleep 5 seconds!
function-->task_a runing 5.00492787361145 seconds!
[tracker]:function-->proxy_fun all steps runing completed!

Process finished with exit code 0

此处 等价于 record_StepLog(how_long_time(task_a))

代参装饰器

待补充

类装饰器

待补充

======================================= over ===========================================

你可能感兴趣的:(Python编程,python,装饰器,decorator)