欢迎访问宙启技术站
智能推送

装饰器函数的高级使用

发布时间:2023-06-22 16:54:34

装饰器是 Python 中的一个重要概念,它可以让我们在不改变原函数代码的情况下,增加原函数的功能和灵活性。常用的装饰器包括 @staticmethod、@classmethod、@property 等,这些装饰器能够让类的方法变得更加灵活和易用。

除了基本的装饰器使用方法之外,我们还可以将装饰器嵌套起来,来实现更加强大的装饰器功能。

例如,我们可以定义一个叫做 log 的装饰器,用来打印函数的运行时间和输入输出结果:

import functools
import time

def log(func):
    @functools.wraps(func)
    def wrapper(*args, **kw):
        start_time = time.time()
        result = func(*args, **kw)
        end_time = time.time()
        print('%s() -> %s (running time: %.6f s)' % (func.__name__, result, end_time - start_time))
        return result
    return wrapper

@log
def my_func(x, y):
    return x + y

print(my_func(1, 2))

通过调用 @log 装饰器,我们可以在函数运行前后打印出函数运行时间和输入输出结果。

此外,我们还可以定义一个叫做 retry 的装饰器,用来在函数失败时自动重试多次,以防止因为网络或其他原因导致的函数执行失败:

import functools
import time

def retry(max_retry, wait_time):
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kw):
            retry_count = 0
            while True:
                try:
                    result = func(*args, **kw)
                    return result
                except Exception as e:
                    if retry_count < max_retry:
                        retry_count += 1
                        time.sleep(wait_time)
                    else:
                        raise e
        return wrapper
    return decorator

@retry(max_retry=3, wait_time=1)
def my_func(url):
    # some code here
    return result

print(my_func('http://example.com'))

通过调用 @retry(max_retry, wait_time) 装饰器,我们可以在函数执行失败时自动重试多次。

以上是装饰器的高级用法,通过嵌套装饰器,我们可以灵活地为函数添加多种功能,让函数的实用性和可重用性大大提高。