Python 函数装饰器

Python 函数装饰器

Python function decorator 函数装饰器的典型行为:把被装饰的函数替换成新函数,二者接受相同的参数,而且(通常)返回被装饰的函数本该返回的值,同时还会做些额外操作。它不修改原来的函数,还给函数增加新的功能,而是使得调用原函数的时候附加一些功能。

记录函数执行时间
import random
import time


# 记录函数执行时间
def logging_time(func):
    def logger(*args, **kwargs):
        print(f"{func.__name__} starts")
        start_t = time.time()
        value_returned = func(*args, **kwargs)
        end_t = time.time()
        print(f"{func.__name__} ends; used time: {end_t - start_t:.2f} s")
        return value_returned
    return logger


@logging_time
def func2():
    delay = random.randint(3, 5) * 0.1
    time.sleep(delay)


def test_func2():
    func2()
缓存函数执行结果

对于一些耗时计算,可以使用函数装饰器来缓存执行结果

import time


def logging_time(func):
    def logger(*args, **kwargs):
        print(f"{func.__name__} starts")
        start_t = time.time()
        value_returned = func(*args, **kwargs)
        end_t = time.time()
        print(f"{func.__name__} ends; used time: {end_t - start_t:.2f} s")
        return value_returned
    return logger


def memoize(func):
    cache = {}

    def wrapper(*args):
        if args in cache:
            return cache[args]
        result = func(*args)
        cache[args] = result
        return result
    return wrapper


def fibonacci(n):
    return n if n <= 1 else fibonacci(n-1) + fibonacci(n-2)


@memoize
def fibonacci_with_cache(n):
    return n if n <= 1 else fibonacci_with_cache(n-1) + fibonacci_with_cache(n-2)


@logging_time
def func1():
    print(f"fibonacci(36) = {fibonacci(36)}")


@logging_time
def func2():
    print(f"fibonacci_with_cache(300) = {fibonacci_with_cache(300)}")


def test_fibonacci():
    func1()
    func2()
# 输出
func1 starts
fibonacci(36) = 14930352
func1 ends; used time: 3.64 s
func2 starts
fibonacci_with_cache(300) = 222232244629420445529739893461909967206666939096499764990979600
func2 ends; used time: 0.00 s
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值