【发布时间】: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