装饰器及其在实际项目中的应用(日志模块,代码计时器,内存跟踪器,超时警告)

1.什么是装饰器

顾名思义,装饰器是通过装饰供能来丰富函数或类的实现功能,并且减少了代码的耦合性,使得代码看起来更加简洁。
简单示例:

2.装饰器的类型

2.1函数装饰器

函数装饰器是针对于函数进行装饰,使得函数的供能进行丰富。它通过闭包来实现,将要装饰的函数作为外层函数的参数传入,将该函数在内层函数中进行执行并增加附加功能,然后将内层函数作为结果返回。如下示例:
不需要传参数的函数装饰器

from time import sleep,time


def decorator(func):
    def wrapper():
        start = time()
        func()
        end = time()
        cost_time = end-start
        print('this func cost time{}'.format(cost_time))
    return wrapper


@decorator
def func_1():
    sleep(1)


@decorator
def func_2():
    sleep(3)

if __name__ == '__main__':
    func_1()
    func_2()

执行结果如下:
this func cost time1.0053126811981201
this func cost time3.009956121444702
可以看出通过一个装饰器我们可以实现对于多个函数实现相同的函数功能。
需要传参数的函数装饰器
很多情况下我们写的装饰器供能较为复杂,就需要传递参数进去,这时使用的闭包为三层,需要在最外层函数decorator(param)传递参数进去,次外层dec(func)将需要装饰的函数作为参数传递进去并将最内层函数wrapper返回,内层函数需要执行

from time import sleep,time


def decorator(param=None):
    def dec(func):
        def wrapper(*args, **kwargs):
            start = time()
            func(*args, **kwargs)
            end = time()
            cost_time = end-start
            print('this func cost time{}'.format(cost_time))
            print('传入的参数为--------{}'.format(param))
        return wrapper
    return dec


@decorator('卡哇伊噢')
def func_1():
    sleep(1)


if __name__ == '__main__':
    func_1()

执行结果为:
this func cost time1.0152842998504639
传入的参数为--------卡哇伊噢
保留函数元信息的装饰器
对于定义的函数都携带有函数的基本信息,如函数名函数说明文档等:函数名.name,函数名.doc,但是当使用前面定义的装饰器后情况会有所不同,如下示例:

from time import sleep,time


def decorator(param):
    def dec(func):
        def wrapper(*args, **kwargs):
            start = time()
            func(*args, **kwargs)
            end = time()
            cost_time = end-start
            print('this func cost time{}'.format(cost_time))
            print('传入的参数为--------{}'.format(param))
        return wrapper
    return dec


@decorator('卡哇伊噢')
def func_1():
    """
    睡眠
    :return:
    """
    sleep(1)


if __name__ == '__main__':
    func_1()
    print('func_1的函数名为:', func_1.__name__)
    print('函数文档:', func_1.__doc__)

代码执行结果如下:

this func cost time1.0033156871795654
传入的参数为--------卡哇伊噢
func_1的函数名为: wrapper
函数文档: None

在python中functools模块提供了@wraps来保存元信息,即对内层函数使用装饰器@wraps(func),即可保留函数func的元信息。

from time import sleep,time
from  functools import wraps

def decorator(param):
    def dec(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            start = time()
            func(*args, **kwargs)
            end = time()
            cost_time = end-start
            print('this func cost time{}'.format(cost_time))
            print('传入的参数为--------{}'.format(param))
        return wrapper
    return dec


@decorator('卡哇伊噢')
def func_1():
    """
    睡眠
    :return:
    """
    sleep(1)


if __name__ == '__main__':
    func_1()
    print('func_1的函数名为:', func_1.__name__)
    print('函数文档:', func_1.__doc__)

代码执行结果如下:

this func cost time1.004314661026001
传入的参数为--------卡哇伊噢
func_1的函数名为: func_1
函数文档: 
    睡眠
    :return:

2.2类装饰器

2.3内置静态装饰器

在python中内置了一些装饰器,我们可以直接调用:@staticmethod,@classmethod,@property等。
@staticmethod 静态装饰器,被装饰的函数不需要传递对象self和自身类cls,和使用普通函数一样。
@classmethod类方法,需要在第一个参数位置传入自身的类cls,
@property 把类内方法当成属性来使用,必须要有返回值,需要传递.
示例如下:

class Space:
    classfunc = '实现space'
    def __init__(self, drawing_id:int=0, drawing_name:str=''):
        self.drawing_id = drawing_id
        self.drawing_name = drawing_name

    @staticmethod
    def get_task_type():
        print('这是一个处理空间的类定义')

    @property
    def get_drawing_name(self):
        return self.drawing_name

    @classmethod
    def get_func(cls):
        print(cls.classfunc)


if __name__ == '__main__':
    space = Space(5432, '地下一层平面图')
    # staticmethod的使用
    space.get_task_type()
    print('property:', space.get_drawing_name)
    space.get_func()

执行结果如下:

这是一个处理空间的类定义
property: 地下一层平面图
实现space

3.装饰器的实际应用

装饰器在实际项目中的应用以下为几个示例:

3.1 使用装饰器来写日志模块

在日志模块使用了python内置的装饰器来实现,并且当我们的日志需要一些固定的处理时,也可使用装饰器来实现。
使用内部装饰器:

# coding: utf-8
"""
此文档为练习装饰器而编写的日志类模块
"""
import json
import traceback
from enum import Enum
import logging

class LogTagClass:

    def __init__(self, task_id=None, type_id=None, x_called_id=None):
        self.task_id = task_id
        self.type_id =type_id
        self.x_called_id = x_called_id
        self.img_path = ''

    def get(self):
        """
        拼接展示前缀信息
        :return: log前缀
        """
        lt = ""
        called_id = ''
        if self.x_called_id:
            called_id= f'[{self.x_called_id}]'
        if self.task_id:
            if lt:
                lt+=', '
            lt += f'fileTaskId:{self.task_id}'
        if self.type_id:
            if lt:
                lt += ', '
            lt += f"type_id:{self.type_id}"
        if not lt:
            return ""
        return f"x_called_id:{called_id}----{lt}-----"


class LogLevel(Enum):
    DEBUG = 10
    INFO = 20
    WARING = 30
    ERROE = 40
    CRITIAL = 50


logger = logging.getLogger("my_life")


class Log:
    tag = LogTagClass()
    default_log_level = LogLevel.INFO

    @classmethod
    def log(cls, msg:str, level: LogLevel=default_log_level, **kwargs):
        """

        :param msg: 日志记录的信息
        :param level: 日志的等级
        :param kwargs:
        :return:
        """
        lv = level.value
        pre_message = cls.tag.get()
        mg = f"{pre_message}---msg:{msg}"
        logger.log(lv, mg, **kwargs)

    @classmethod
    def _log_with_code(cls, code:int, level:LogLevel, exc:Exception=None, exc_msg:str=None, **kwargs):
        """
        处理异常的私有方法
        :param code: 错误码
        :param level: 异常等级
        :param exc: 异常
        :param exc_msg: 额外信息
        :return:
        """
        if code == '0000':
            cls.log('success')
        else:
            priv_exception = PriException(code)
            if level > LogLevel.WARING:
                msg1, msg2 = "", ""
                if exc is not None:
                    if level == LogLevel.ERROE:
                        msg1 = str(exc)
                    else:
                        msg1 = f"traceback:{traceback.format_tb()}---exc:{str(exc)}"
                    if exc_msg is not None:
                        msg2 = exc_msg
                priv_exception.msg.sub_msg = f'{msg1}------{msg2}'
            else:
                priv_exception.msg.sub_msg = exc_msg
            msg = priv_exception.__str__()
            cls.log(msg, level, **kwargs)


    @classmethod
    def error_log(cls, code: int, exc: Exception=None, msg:str=None):
        """
        error 日志输出
        :param code: 错误码
        :param exc: 异常
        :param msg: 额外信息
        :return:
        """
        return cls._log_with_code(code, LogLevel.ERROE, exc, msg)


"""
接下来定义的是一个error文件
"""
class PriException:

    def __init__(self, error_code:int):
        msg = _error_msg_from_code(error_code)
        self.msg = ErrorMsg(error_code,msg)


class ErrorMsg(dict):
    def __init__(self, error_code:int, msg:str, sub_msg:int=None):
        """
        错误提
        :param error_code:错误码
        :param msg: 错误信息
        :param sub_msg: 额外的附加信息
        """
        super().__init__()
        self.code = error_code
        self.msg = msg
        self.sub_msg = sub_msg

    def __str__(self):
        return json.dumps(self.__dict__)


def _error_msg_from_code(error_code):
    """
    内部函数,从错误码中获取错误信息
    :param error_code: 错误码
    :return: 提示信息
    """
    # 获取是哪一类错误
    type = error_code/1000
    # 获取是该类错误中的哪一个码对应的错误,通过对应的字典关系获取错误提示信息
    error = error_code%1000
    return "i am a error!!!"

3.2使用装饰器来跟踪内存使用情况

3.3使用装饰器来实现代码运行计时器

在项目中很多时候需要观察代码处理某个环节的时长

import datetime
from functools import wraps
from time import time,sleep


def timer(tag):
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            start_time = time()
            print()
            print('='*20 + '{}.{}----start_time{}'.format(tag, func.__name__, datetime.datetime.now()) + '='*20)
            result = func(*args, **kwargs)
            end_time = time()
            print('='*20 + '{}.{}----costtime{:.2f}seconds'.format(tag, func.__name__, end_time-start_time) + '='*20)
            print('=' * 20 + '{}.{}----end_time{}'.format(tag, func.__name__, datetime.datetime.now()) + '=' * 20)
            return result
        return wrapper
    return decorator


@timer('my_daily')
def go_to_bed():
    sleep(2)
    print("this is the time to have a lunch")


if __name__ == "__main__":
    go_to_bed()

运行结果

3.4超时警告

3.5运行环境的检查

3.6缓存权限

3.7事务处理

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个基于Android的购物车项目计时器代码示例: ```java public class TimerActivity extends AppCompatActivity { private TextView mTimerTextView; private Button mStartButton; private Button mStopButton; private CountDownTimer mCountDownTimer; private long mTimeLeftInMillis; private boolean mTimerRunning = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_timer); mTimerTextView = findViewById(R.id.timer_text_view); mStartButton = findViewById(R.id.start_button); mStopButton = findViewById(R.id.stop_button); mStartButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startTimer(); } }); mStopButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { stopTimer(); } }); } private void startTimer() { mTimeLeftInMillis = 600000; // 10 minutes mCountDownTimer = new CountDownTimer(mTimeLeftInMillis, 1000) { @Override public void onTick(long millisUntilFinished) { mTimeLeftInMillis = millisUntilFinished; updateTimer(); } @Override public void onFinish() { mTimerRunning = false; mStartButton.setEnabled(true); mStopButton.setEnabled(false); Toast.makeText(TimerActivity.this, "Time's up!", Toast.LENGTH_SHORT).show(); } }.start(); mTimerRunning = true; mStartButton.setEnabled(false); mStopButton.setEnabled(true); } private void stopTimer() { if (mCountDownTimer != null) { mCountDownTimer.cancel(); } mTimerRunning = false; mStartButton.setEnabled(true); mStopButton.setEnabled(false); } private void updateTimer() { int minutes = (int) (mTimeLeftInMillis / 1000) / 60; int seconds = (int) (mTimeLeftInMillis / 1000) % 60; String timeLeftFormatted = String.format(Locale.getDefault(), "%02d:%02d", minutes, seconds); mTimerTextView.setText(timeLeftFormatted); } } ``` 上述代码,我们创建了一个名为`TimerActivity`的Activity,并在其实现了一个简单的计时器计时器使用了Android提供的`CountDownTimer`类来实现,它会每隔一定时间(这里是1秒)回调一次`onTick`方法,在这个方法更新倒计时的文本。在启动计时器时,我们设置了计时器的总时间为10分钟(即600000毫秒),并在计时器结束时弹出一个提示框。我们还实现了两个按钮,分别用于启动和停止计时器。在启动计时器时,我们禁用了启动按钮,并启用了停止按钮,以防止用户重复启动计时器。在停止计时器时,我们取消了计时器,并将按钮状态恢复到初始状态。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值