473,406 Members | 2,707 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,406 software developers and data experts.

list of class instances within a list of a class instances

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
Jul 18 '05 #1
2 1953
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

Jul 18 '05 #2
> 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
Jul 18 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: Crawley | last post by:
Im trying to create a list of lists and for some reason its not working: class Tile: _next = { 'n':None, 'ne':None, 'e':None, 'se':None, 's':None, 'sw':None, 'w':None, 'nw':None } def...
6
by: Brian Jones | last post by:
I'm sure the solution may be obvious, but this problem is driving me mad. The following is my code: class a(object): mastervar = def __init__(self): print 'called a'
1
by: NickB | last post by:
Please could someone tell me what is wrong. Ther error is: An unhandled exception of type 'System.NullReferenceException' occurred in microsoft.visualbasic.dll Additional information: Object...
30
by: Neil Zanella | last post by:
Hello, Suppose I have some method: Foo::foo() { static int x; int y; /* ... */ }
6
by: JustSomeGuy | last post by:
I have an stl list that grows to be too huge to maintain effectivly in memory. There are elements within the list that could be stored on disk until accessed. However I don't want to expose...
5
by: Kenneth | last post by:
<list> seems to be a powerful structure to store the related nodes in memory for fast operations, but the examples I found are all related to primitive type storage. I'm doing a project on C++...
90
by: Christoph Zwerschke | last post by:
Ok, the answer is easy: For historical reasons - built-in sets exist only since Python 2.4. Anyway, I was thinking about whether it would be possible and desirable to change the old behavior in...
5
by: jung_h_park | last post by:
From: jung_h_park@yahoo.com Newsgroups: microsoft.public.dotnet.framework.aspnet Subject: Dropdown List not retaining its SelectedValue Date: Mon, 26 Jun 2006 21:02:57 -0700 Hello, My...
6
by: David C | last post by:
In my business layer, I have Person, and Patient which derives from Person. //base class for all single classes public class BaseItem{} public class Person:BaseItem{} public class...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.