list of class instances within a list of a class instances

Peter Otten __peter__ at web.de
Sun Feb 22 03:14:30 EST 2004


John Wohlbier wrote:

> class primaryClass:

Remove the following two lines. Variables you put here are shared between
all instances of the class.

>      name=""
>      sClasses = []
> 
>      def __init__(self,name):
           self.sClasses = [] # now you'll get a new list for each instance
>          self.name = name
>          self.sClasses.append(subClass("default"))
>
###############################################################################
> class subClass:

The following line is superfluous.

>      name=""
> 
>      def __init__(self,name):
>          self.name = name
> 
>
###############################################################################

> 
> 
> port = [] # make a list
> port.append(primaryClass("firstclass"))
> 
> print 'port contents'

More idiomatic is:
for p in port:
    print p.name
    for s in s.sClasses:
        #...
Or, if you really need the indices:

for i, p in enumerate(port):
    print i, p.name
    #...

> 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"))

Hey, I've seen the following section before. Never duplicate code - that's
what functions are for.

> 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


Peter




More information about the Python-list mailing list