0

In the below code children array stores treeNode objects. I have created function variable inside treeNode object which stores the function for that object as shown below in the code. The two prints below are printing different things but they should print the same output which is making me confused on why it is happening.

attr_values = [-2, -1,  0,  1,  2,  3,  4,  5,  6,  7,  8]
children_arr = [None]*5
for j in range(5):  #create child node
    children_arr[j] = treeNode()
    f = lambda y: y==attr_values[j]
    children_arr[j].function=f
    print(children_arr[j].function(-2))

for k in range(5):
    print(children_arr[k].function(-2))

print1: True False False False False False False False False False False

print2: False False False False False False False False False False False

EDIT: a_guest in comments solved my problem.

Gulshan Jangid
  • 463
  • 4
  • 7
  • ok even after finding out this as duplicate, I am unable to understand what to do in my case. Can anyone help? – Gulshan Jangid Mar 31 '19 at 00:09
  • You need to move it to a new scope, for example via generating function: `def generate(v): return lambda y: y == v` and then `children_arr[j].function = generate(attr_values[j])`. Or you can just use `children_arr[j].function = attr_values[j].__eq__`. – a_guest Mar 31 '19 at 00:36
  • Thanks a lot. You just saved me a headache! – Gulshan Jangid Mar 31 '19 at 00:46

0 Answers0