0
class Func:
    def __init__(self):
        self.weight = 0
class Skill:
    def __init__(self, bson):
        self.f = [Func()]*5
        for i in range(0,5):
            self.f[i].weight = bson['w'+str(i+1)]
d = {"w1":20,"w2":0,"w3":0,"w4":0,"w5":0}

s = Skill(d)
print s.f[0].weight

The output is 0 rather than 20. I am always hard to figure out the difference of class member and object member in python.

jean
  • 2,825
  • 2
  • 35
  • 72

1 Answers1

3

You should not create the list of Func in this way

self.f = [Func()]*5

You should use a list comprehension or some other method

self.f = [Func() for _ in range(5)]

In the first method, you are creating a list of length 5, with all elements pointing to the same instance of a Func. You don't want this, you want to create a list of 5 different instances of Func.

Cory Kramer
  • 114,268
  • 16
  • 167
  • 218