python-装饰器

python-装饰器

当一个函数中,不同逻辑混杂在一起的时候,程序的可读性会大打折扣。这个时候,可以考虑用一种叫做“装饰器”的东西来重新整理代码。

def xx1(被装饰函数):
def xx2(如果被装饰函数有参数那么输入):
xxxxxxxxxxxxxxx
被装饰函数(如果被装饰函数有参数那么输入)
xxxxxxxxxxxxxxx
如果被装饰函数中含有reture则需要返回被装饰函数
没有则不需要
reture xx2

没有返回值的函数

import time


def display_time(func):
    """
    记录时间装饰器
    :return:
    """

    def function():
        t1 = time.time()
        func()
        print(time.time() - t1)

    return function


@display_time
def count_run_number():
    for i in range(1, 1000):
        print(i)


count_run_number()

带有返回值的函数

import time


def display_time(func):
    """
    记录时间装饰器
    :return:
    """

    def function():
        t1 = time.time()
        result = func()
        print(time.time() - t1)
        return result

    return function


@display_time
def count_run_number():
    count = 0
    for i in range(1, 100000):
        if i % 2 == 0:
            count += 1
    return count


count_run_number()

带有参数的函数

import time


def display_time(func):
    """
    记录时间装饰器
    :return:
    """

    def function(*args,**kwargs):
        t1 = time.time()
        result = func(*args,**kwargs)
        print(time.time() - t1)
        return result

    return function


@display_time
def count_run_number(num):
    count = 0
    for i in range(1, num):
        if i % 2 == 0:
            count += 1
    return count


count_run_number(100000000)
posted @ 2021-07-06 22:12  chron  阅读(54)  评论(0)    收藏  举报