473,789 Members | 2,467 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 "primaryCla ss"
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(subClas s()) 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,n ame):
self.name = name
self.sClasses.a ppend(subClass( "default"))
############### ############### ############### ############### ############### ####
class subClass:
name=""

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

############### ############### ############### ############### ############### ####
port = [] # make a list
port.append(pri maryClass("firs tclass"))

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(pri maryClass("seco ndclass"))
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(pri maryClass("thir dclass"))
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 1971
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,n ame): self.sClasses = [] # now you'll get a new list for each instance self.name = name
self.sClasses.a ppend(subClass( "default"))
############### ############### ############### ############### ############### #### class subClass:
The following line is superfluous.
name=""

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

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


port = [] # make a list
port.append(pri maryClass("firs tclass"))

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(pri maryClass("seco ndclass"))
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(pri maryClass("thir dclass"))
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,n ame):
self.name = name
self.sClasses.a ppend(subClass( "default"))


Try the below instead.

class primaryClass:
def __init__(self,n ame):
self.name = name
self.sClasses = [subClass("defau lt")]

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.n ame' object,
it is referring to the object assigned. When you used
self.sClasses.a ppend(), 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
1823
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 blankGridCanvas( maxx, maxy ): grid = for y in xrange( 0, maxy ):
6
3196
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
2090
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 variable or With block variable not set. I am trying to print the contents of a list box on another form. This is the sub, and the highlighted line is where it is falling over.
30
2278
by: Neil Zanella | last post by:
Hello, Suppose I have some method: Foo::foo() { static int x; int y; /* ... */ }
6
1651
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 this to the application class. How can I extent the stl list to write some elements to disk when they are put in the list and read them from disk when they are read from the list.
5
6254
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++ with my defined classes to be added to linked list structure so as to facilitate the operation of all instances of defined classes. Is that possible to apply such classes to <list> or <Vector> structure? Thanks!
90
10825
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 future Python versions and let dict.keys() and dict.values() both return sets instead of lists. If d is a dict, code like: for x in d.keys():
5
11903
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 dropdown list control does not retain its SelectedValue. Unless I read the SelectedValue right after the control has been loaded, populated, and assigned with its original value (and of course that is
6
1300
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 Patient:Persons{}
0
10193
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10136
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9979
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9016
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7525
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5415
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5548
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3695
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2906
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.