list of class instances within a list of a class instances

Josiah Carlson jcarlson at nospam.uci.edu
Sun Feb 22 03:41:35 EST 2004


> class primaryClass:
>     name=""
>     sClasses = []
> 
>     def __init__(self,name):
>         self.name = name
>         self.sClasses.append(subClass("default")) 

Try the below instead.

class primaryClass:
     def __init__(self,name):
         self.name = name
         self.sClasses = [subClass("default")]

In general, everything defined in the class-level scope is shared among 
all instances of that class, even before creation.  When you re-assign 
'name' in __init__ in your original version, or really anywhere else, 
'name' is no longer referring to the shared 'primaryClass.name' object, 
it is referring to the object assigned.  When you used 
self.sClasses.append(), you were modifying the shared list in-place, 
which is why all instances of primaryClass shared the list.

Also, you don't need to define all class variables (or really any) 
outside in the class-level scope.  It is convenient for some shared 
immutables (strings, integers, tuples, floats, functions) on occasion, 
but unless you know what you are doing with the mutables (lists, 
dictionaries, arrays (from the array module), etc.), you should be careful.

  - Josiah



More information about the Python-list mailing list