One of my function will use external variables, but the external variables will change when I use this function. Here is an example:
func_list=[]
for i in range(0,6):
def func():
print(i)
func_list.append(func)
for j in range(0,6):
func_list[j]()
I hope the output is [1,2,3,4,5,6], but the real output is [6,6,6,6,6,6] I know one of solution is using closure, like this:
func_list=[]
for i in range(0,6):
def create_func():
nonlocal i
number=i
def func():
print(number)
return func
func=create_func()
func_list.append(func)
for j in range(0,6):
func_list[j]()
This programs could output [1,2,3,4,5,6]. But it looks a bit ugly. It use additional 4, at least 3, lines to solve this problem...Is there some more simple methods/function decorations to solve this problem?
thank you.