如何在Python中生成正确的闭包函数



我想创建一个返回另一个函数的函数,该函数根据第一个函数的参数生成一些随机数,我做了以下代码,但我得到了消息"闭包未定义":

def func1(current_price, y, z)
def closure ()
future_price = random.gauss(0,1)+Current_price+y+z
return future_price
return closure

这个想法是,每次我调用closure((时,它都会根据公式生成一个数字,下一次我调用cloture((时的结果应该基于上一个结果,将future_price的结果读取为current_price。

感谢任何关于如何处理这个问题的建议。

即使在将return closure()更改为return closure之后,闭包在调用之间也不会记住future_price的值,因为它是一个局部变量,每次调用都会重新创建。您需要func1中初始化future_price,然后将其用作闭包中的非局部变量。

def func1(current_price, y, z):
future_price = current_price
def closure():
nonlocal future_price
future_price = random.gauss(0,1) +future_price+ y + z
return future_price
return closure

一旦定义了func1,每个调用都将创建一个新函数,该函数有自己的future_price要更新。

f = func1(10, 1, 2)
g = func1(20, 1, 1)

您可以通过深入研究function对象的一些内部结构来了解闭包的作用。

>>> [x.cell_contents for x in f.__closure__]
[10, 1, 2]
>>> [x.cell_contents for x in g.__closure__]
[20, 1, 1]
>>> f()
14.471922798379957
>>> g()
21.911981360352744
>>> [x.cell_contents for x in f.__closure__]
[14.471922798379957, 1, 2]
>>> [x.cell_contents for x in g.__closure__]
[21.911981360352744, 1, 1]
>>>

最新更新