【问题标题】:Create a decorator in Python, which remembers last output of the function在 Python 中创建一个装饰器,它会记住函数的最后输出
【发布时间】:2021-08-21 13:18:56
【问题描述】:

我需要创建一个装饰器来记住它所装饰的函数的最后调用结果。比如我有一个函数:

def summarize(*args):
    result = ""
    for i in args:
        result += i
    print('New result = ', result)
    return result

而且我需要使用装饰器(没有任何类或其他东西),使它像这样:

summarize("he", "llo")
>>> "Previous result = 'None'"
>>> "New result = 'hello'"
summarize("good", "bye")
>>> "Previous result = 'hello'"
>>> "New result = 'goodbye'"

我是装饰器的新手,现在我不知道如何做到这一点。只有当我尝试在一次运行中调用该函数两次时,我才会得到所需的结果。

【问题讨论】:

  • “一次调用两次函数”是什么意思?如果在两次调用函数之间调用了任何其他函数,是否应该清除缓存?你为什么不想使用一个类?您认为“smth”类似于类的什么?
  • @MisterMiyagi 我的意思是,我不需要它那样工作:summarize('he', 'llo') summarize('good', 'by') --run the code-- "Previous result = 'None'" "New result = 'hello'" "Previous result = 'hello'" "New result = 'goodbye'" 我希望它适用于每个新代码运行,如果你明白我的意思的话

标签: python function caching decorator


【解决方案1】:

见下文:

def historic_results(func):
    # retrive historic outputs from hitoric_outputs.txt file if it exists
    with open('historic_outputs.txt', "r") as f:
        try:
           previous_outputs = f.readlines()
        except:
           previous_outputs = []

    def inner(*args, **kwargs):
        
        if not previous_outputs : print("Previous Result:", None)
        if previous_outputs: 
            for item in previous_outputs: print("Previous Result:", item)

        # append the output in the historic outputs txt file
        with open('historic_outputs.txt', 'a') as f:
            f.write(func(*args, **kwargs) + "\n")
        
        print("New Result", func(*args, **kwargs))

        return func(*args, **kwargs)

    return inner


@historic_results
def summarize(*args):
    result = ""
    for i in args:
        result += i
    return result

测试:

summarize("hel", "lo")
summarize("Ami", "ne")
summarize("stupid", "_beaver")

输出:

Previous Result: None
New Result hello

Previous Result: hello
New Result Amine

Previous Result: hello
Previous Result: Amine
New Result stupid_beaver

【讨论】:

  • 感谢您的帮助,但是否有可能不是针对代码中的一个一个函数调用,而是针对同一函数的每次新运行?
  • 结果可以存储在函数、闭包或字典中,这也允许每个函数单独缓存。无需使用global
  • @stupid_beaver 它适用于每个新的函数调用/运行
  • @AmineBTG 我的意思是,每个代码都可以运行吗?不只是在代码中多次调用函数
  • 为了让每个代码都运行在主机上,您需要将历史输出存储在某种文件或数据库中。这是你要找的吗?
猜你喜欢
  • 2010-09-23
  • 2017-11-16
  • 2020-02-03
  • 2018-06-07
  • 1970-01-01
  • 2021-06-22
  • 2020-04-27
  • 1970-01-01
  • 2015-03-28
相关资源
最近更新 更多