【问题标题】:python decorating recursive functionpython装饰递归函数
【发布时间】:2022-01-01 06:18:45
【问题描述】:

我正在尝试使用我的 timer_func 装饰器来记录斐波那契函数的处理时间。但看起来装饰器正在记录多次:

def timer_func(func):
    def inner_func(*args):
        t1 = perf_counter()
        res = func(*args)
        t2 = perf_counter()
        logging.log(logging.INFO, f"Done in {t2 - t1} Seconds!")
        return res

    return inner_func


@timer_func
def fibonacci(x: int):
    if x > 2:
        return fibonacci(x - 1) + fibonacci(x - 2)
    elif x == 1 or x == 2:
        return 1


r = timer_func(fibonacci)(5)
print("Fibonacci %d of is %d" % (5, r))

输出:

Done in 7.269991328939795e-07 Seconds!
Done in 7.840008038328961e-07 Seconds!
Done in 0.00013806700007990003 Seconds!
Done in 0.0006901449996803422 Seconds!

【问题讨论】:

  • 可能是因为你多次调用它?
  • 你还要装饰两次
  • 创建一个包装器函数,它只调用未修饰的 fib 函数并修饰包装器。
  • 这是一个练习吗?因为否则 Python 已经有一个用于计时函数的装饰器。见stackoverflow.com/q/7370801/839733
  • @AbhijitSarkar 是的。我不想用那个

标签: python python-decorators


【解决方案1】:

每次调用fibonacci 函数时都会生成日志。由于该函数是递归的,因此会被多次调用。

您需要制作具有装饰器并调用非装饰函数的函数的第二个版本。例如:

@timer_func
def fibonacci(x: int):
    return _fibonacci(x)


def _fibonacci(x: int):
    if x > 2:
        return _fibonacci(x - 1) + _fibonacci(x - 2)
    elif x == 1 or x == 2:
        return 1

【讨论】:

    【解决方案2】:

    即使在用 @ 装饰了函数之后,你仍然只是在装饰

    r = fibonacci(5)
    

    会的。

    【讨论】:

      猜你喜欢
      • 2012-06-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-20
      • 2020-01-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多