【问题标题】:Decorator to output average of historical inputs and outputs to function装饰器输出历史输入和输出的平均值以发挥作用
【发布时间】:2022-01-01 16:32:57
【问题描述】:

我的函数接受一个整数作为输入并输出一个整数。我需要编写一个装饰器来包装它们。

装饰器将保存一个包含两个数字的元组:输入的平均值和输出的平均值。对于此类函数的每次调用,都会打印平均值。

我不太确定路。我试过这个,但它只返回当前函数调用的相同输入和输出,我如何计算到目前为止所有输入和输出的平均值?或者我如何保留下次调用装饰器的 args 数量?

def dec(func):
    def wrap(*args):
        counter = len(args)
        avg_input = sum(args) / counter
        avg_output = func(*args)
        print("Average of inputs ", avg_input)
        print("Average of outputs ", avg_output)
    return wrap


@dec
def func(num):
    return num * 2


func(2) # now the avg_inputs = 2 and avg_outputs = 4
func(4) # now the avg_inputs = 3 and avg_outputs = 6
func(6) # now the avg_inputs = 4 and avg_outputs = 8

当前输出为:

Average of inputs  2.0
Average of outputs  4
Average of inputs  4.0
Average of outputs  8
Average of inputs  6.0
Average of outputs  12

而我真正需要的输出是:

Average of inputs  2.0
Average of outputs  4
Average of inputs  3.0
Average of outputs  6
Average of inputs  4.0
Average of outputs  8

【问题讨论】:

  • 假设您在多个函数上使用相同的装饰器。您是否希望将平均值分开,例如 fun1fun2,还是希望它们的总数相同?
  • 你想用一个整数来划分一个元组?您的问题不在于装饰器的工作方式,问题在于您的代码没有计算任何平均值。它也不会累积以前调用该函数的任何结果,但这也不是装饰器特有的问题。
  • @CrazyChucky 相同总数

标签: python decorator wrapper


【解决方案1】:
from functools import wraps

def dec(func):
    @wraps(func)
    def wrap(*args):
        wrap.counter += 1
        wrap.sum_inputs += int(*args)
        wrap.sum_outputs += func(*args)
        avg_input = wrap.sum_inputs / wrap.counter
        avg_output = wrap.sum_outputs / wrap.counter
        print("Average of inputs ", avg_input)
        print("Average of outputs ", avg_output)
        return func(*args)
    wrap.counter = 0
    wrap.sum_inputs = 0
    wrap.sum_outputs = 0
    return wrap

【讨论】:

  • 我看到您能够找到自己问题的答案。干得好!你介意添加一点关于它是如何工作的解释吗?这将有助于这个答案在未来对遇到这个问题的其他人有用。
猜你喜欢
  • 2023-03-21
  • 1970-01-01
  • 1970-01-01
  • 2020-01-16
  • 1970-01-01
  • 2018-02-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多