initializing various instances of a class with a loop

Hi. I’m still a newbie at this python thing. I have a problem:

I have 2 classes, say class “A” and “B”. The thing is, when class A initializes itself, it also initializes a lot of instances of class B. Class A has a list that keeps track of the name of the class B instances it “contains”, and each instance of B holds a list of some other data. So init 's for class A and B go something like this:


class A():
   instances = []
   def __init__(self, x):
      for i in range(x):
         b = B()
         self.instances.append(b)

class B():
   variables = []
   def __init__():
      pass

The thing is, that the list on class B needs to be updated right away after the class is initialized, and I do that with the code from class A’s init, something like this:


class A():
   instances = []
   def __init__(self, x):
      for i in range(x):
         b = B()
         self.instances.append(b)
      for i in range(len(self.instances)):
         self.instances[i].variables.append("some info"+str(i))

class B():
   variables = []
   def __init__():
      pass

But then when I print any of the B instances “variables” list, I get that each “variable” holds the information for the totality of B instances(in this case, each instance’s “variable” list would be "[some info 1, some info 2, some info 3… and so on and so on, the same for each one), so basically it is always referring to the SAME list.

Can you explain to me what I’m doing wrong? it will be highly appreciated.

thankyou very much.

You are a Java/C++/C# programmer originally, right? :slight_smile: Instance variables need to be assigned through “self.var”, otherwise they are considered class variables (something like static in other languages). Basically you should change your code to:


class A():
   def __init__(self, x):
      self.instances = []
      for i in range(x):
         b = B()
         self.instances.append(b)
      for i in range(len(self.instances)):
         self.instances[i].variables.append("some info"+str(i))

class B():
   def __init__():
      self.variables = []
      pass

hahaha! no! but thank you, I’m flattered… I’m just a guy who realized too late in life what fun programming is. Python is the first language I’ve oficially “learned”(I got through half a C book, and I learnt some ActionScript on “a need to know basis”)

Thanks a lot, I’ll give it a try then.

PS: worked like a charm. thanks again!