0

Given the following class

class sq():
    def __init__(self,func,x):
        self.func = func
        self.x = x 
    def square(self):
        return self.func(self.x)**2
    
y = lambda x,p: x + p
p_ls =  range(1,11)
x = 0

objects = [sq(lambda x: y(x,pi),x) for pi in p_ls]
squares = [sq(lambda x: y(x,pi),x).square() for pi in p_ls]
#[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
squares1 = [obj.square() for obj in objects]
#[100, 100, 100, 100, 100, 100, 100, 100, 100, 100]

i can't understand why squares are not equal to squares1. Its seems like all objects in objects list are using p = p_ls[-1]. Is there a way to "store" func each time the class is called ?

jjkr
  • 1
  • Creating functions in a loop when the function uses the looping variable is problematic. The value of `pi` isn't saved at the time the function is created in this case. `squares` has the right values because you're calculating the final value before changing `pi`. – Carcigenicate Oct 10 '20 at 13:41
  • @Carcigenicate thank you. Not so much understood but it's fine. – jjkr Oct 10 '20 at 13:49
  • To be fair, this isn't a very easy thing to wrap your head around. I had to play around with it for a bit with different examples before it started making sense. – Carcigenicate Oct 10 '20 at 13:50
  • i was playing with different `@property` and `lru_cache()` combinations but after some hours i still didn't manage to make it work. – jjkr Oct 10 '20 at 13:57

0 Answers0