I have the following python3 code
class Test:
pos = [0,0]
actions = []
def bar(self, target):
for i in target:
def _():
print(i,end="")
self.actions.append(_)
foo = Test()
foo.bar("abcd")
for i in foo.actions:
i()
Which is meant to output:
abcd
but instead it outputs:
dddd
I’m pretty sure the function is using the value of i when executing (the last value i had) and not i’s value the function _ is declared, which is what I want.
>Solution :
The general solution to this is to store the value as a default parameter value, like this:
class Test:
pos = [0,0]
actions = []
def bar(self, target):
for i in target:
def _(i=i): # This is the only changed line
print(i,end="")
self.actions.append(_)
foo = Test()
foo.bar("abcd")
for i in foo.actions:
I()
>>> abcd