list of class instances within a list of a class instances

John Wohlbier jdmux at gonomadic.net
Sun Feb 22 07:00:19 CET 2004


Hi,

I have a basic programming question regarding classes
in python. I want to have a list of "primaryClass"
instances, and in each instance of primaryClass I would
like a list of "subClass" instances. When each primaryClass
instance is created I want to put one instance of subClass
into the "sClasses" list (see code). The attached
code is what I came up with, but it doesn't do what I
want. For some reason the "sClasses" list in each primaryClass
instance is the same! That is, when a new primaryClass is instantiated,
and the .append(subClass()) is called in the constructor, the
subClass is appended to ALL instances of primaryClass, instead
of just the new instance of primaryClass. The
print statements in the code confirm this.

I think I must be missing something fundamental. Thanks
in advance.

jgw

======================================================================


###############################################################################
class primaryClass:
     name=""
     sClasses = []

     def __init__(self,name):
         self.name = name
         self.sClasses.append(subClass("default"))
###############################################################################
class subClass:
     name=""

     def __init__(self,name):
         self.name = name

###############################################################################


port = [] # make a list
port.append(primaryClass("firstclass"))

print 'port contents'
for i in range(len(port)):
     print i, port[i].name
     for j in range(len(port[i].sClasses)):
         print i, j, port[i].sClasses[j].name

port.append(primaryClass("secondclass"))
print 'port contents'
for i in range(len(port)):
     print i, port[i].name
     for j in range(len(port[i].sClasses)):
         print i, j, port[i].sClasses[j].name

port.append(primaryClass("thirdclass"))
print 'port contents'
for i in range(len(port)):
     print i, port[i].name
     for j in range(len(port[i].sClasses)):
         print i, j, port[i].sClasses[j].name





More information about the Python-list mailing list