I am trying to instantiate a list, particles, with test2 objects. When I print the length of each test2 object's pBest list after each new object is instantiated it can be seen that every instatiation adds to the same list in memory. Why does each object not have its own member variables in memory?
I have tried making deep copies of newly instantiated objects using self.particles.append(copy.deepcopy(test2(numVariables))), but the same issue occurs.
from test2 import test2
class test:
particles = []
gBest = []
def __init__(self, numParticles, numVariables):
for i in range(0, numParticles):
self.particles.append(test2(numVariables))
for j in self.particles:
print(len(j.pBest))
p = test(5, 2)
import random
class test2:
velocities = []
positions = []
pBest = []
def __init__(self, numVariables):
for i in range(0, numVariables):
self.velocities.append(random.random())
self.positions.append(random.random())
self.pBest.append(float('inf'))
I expect the output to be:
2
2
2
2
2
2
2
2
2
2
2
2
2
2
2
But the output is:
2
4
4
6
6
6
8
8
8
8
10
10
10
10
10