Class with subclass and dynamic lists

Piotr Legiecki piotrlg at sci.pam.szczecin.pl
Thu Jul 26 08:17:40 EDT 2001


Hi

I can't resolve my problem. Here is the test code 

class A:
  x=[] #it will be list of B objects
  z=None #something, doesn't matter

class B:
  y=None 


#this function adds to A object (arg) B objects with value val
def f(arg, val):
  for i in range(1,3): #to put some values into the list
    arg.x.append(B())
    l=len(arg.x)-1      #well, it is just added the last object in a
list, 
    arg.x[l].y=val+i     #assign him somethig
    print 'in f', arg.x[l].y # test
    print l                   #test, here I can see, that my list in
class A (x[]) is THE SAME for all the
                        #A instances! Why?

def main():
  p=[]  #list of class A objects
  p.append(A()) #make 2 objects of class A
  f(p[0], 10)   #send object A, from list of A's objects (I hope) to add
a list of B objects to A object
  p[0].z='aaa'

  p.append(A()) #second A object
  p[1].z='bbb'
  f(p[1],20)

#testing, not good
  print p[0].x[0].y 
  print p[0].x[1].y
  print p[0].z
  print p[1].x[0].y #here I have the same values as in p[0].x[0].y, why?
  print p[1].x[1].y #why p[1].x is the same list for both (p[0], p[1]) A
objects?
  print p[1].z
  print p[0].z

main()

-- 
Regards
Piotr Legiecki



More information about the Python-list mailing list