gpt4 book ai didi

python - 关闭: a function that returns the value of its previous call

转载 作者:行者123 更新时间:2023-12-02 04:01:21 25 4
gpt4 key购买 nike

我正在尝试构建一个函数,该函数使用闭包返回先前调用的值。第一次调用函数时,它将返回 None。我不知道如何将last_in从一个调用更新到另一个调用。

def last_in(x):
last_in = [None]

def get():
temp = last_in[0]
last_in[0] = x
# print(last_in)
return temp
return get()

例如,print(last_in(1),last_in(2),last_in(3)) 应打印:None 1 2

最佳答案

您的方法的问题在于,每当您调用 last_in(即“外部”函数)时,前一个值都会存储在 last_in (数组,而不是函数)中重置为。相反,外部函数应该只调用一次,这样每次调用时该值都不会重置。

不确定你需要这个做什么,但我认为为此创建一个装饰器函数是有意义的,即修改现有函数的函数。这样,所有存储和检索最后结果的操作都可以在装饰器中完成,而不会扰乱实际函数。外部函数(装饰器)仅被调用一次,原始函数将被替换为能够正确检索存储值的装饰版本。

def return_previous(f):
f.last_result = None
def _f(*args, **kwargs):
res = f.last_result
f.last_result = f(*args, **kwargs)
return res
return _f

@return_previous
def some_function(x):
return x**2

print(some_function(1), some_function(2), some_function(3))
# None 1 4

关于python - 关闭: a function that returns the value of its previous call,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59911291/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com