Fabian Fabian - 1 year ago 76
Python Question

How to create "individual" objects

my task is actually pretty simple. Maybe I'm too much used to c++ to not see my fault.
I have two classes and a list.
The list should include all objects made of class1, while class1 also includes a list for all objects of class2.
So we have:

All_Objects1 = [] # For class1 objects

class class1 (object):
All_Objects2 = [] # For class2 objects

class class2 (object):
name = ""
number = 0

Now I do this:

# class1 objects:
obj1= class1()
obj2= class1()

# class2 objects
obj3 = class2()
obj3.name, obj3.number = "hello world", 10
obj4 = class2()
obj4.name, obj3.number = "hello europe", 20
obj5 = class2()
obj5.name, obj3.number = "hello asia", 30
obj6 = class2()
obj6.name, obj3.number = "hello africa", 40

# Attach object3 and object4 to object1

# Attach object5 and object6 to object2

# Attach obj1 and obj2 to the global list.

And finally I do a print for checking if everything is where it belongs:

print (len(All_Objects1[0].All_Objects2)) # Should be 2.
for i in All_Objects1[0].All_Objects2:
print (i.name) # Should be world and europe.

print (len(All_Objects1[1].All_Objects2)) # Should be 2.
for i in All_Objects1[1].All_Objects2: # Should be asia, africa.
print (i.name)

Now the problem is, that every object2 is in every object1 and I have no clue why.

In my actual program I do something like this, what would actually work in c++:

for i in all_information:
if (i==Keyword):
currentObject = class1()

And then I will have some independent objects in my list. But in Python I think I somehow can't overwrite "currentObject".

Thank you so much for your help.

Answer Source

With Python, all class members declared outside any function are static members. So they are shared by each object instantiated from the class.

What you want is the following:

class class1 (object):
    def __init__(self):
        self.All_Objects2 = []  # For class2 objects

class class2 (object):
  def __init__(self):
        self.name = ""
        self.number = 0
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download