0

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
MilkyCode
  • 25
  • 8
  • 1
    Defining variables at class scope makes them class members, not instance members. – MisterMiyagi Aug 13 '19 at 12:16
  • 1
    Possible duplicate of [python class instance variables and class variables](https://stackoverflow.com/questions/8701500/python-class-instance-variables-and-class-variables) – MisterMiyagi Aug 13 '19 at 12:18

1 Answers1

1

pBest is static in your example (it means that all class instances have access to the same variable). Moving it to the constructor will fix it:

class test2:

    def __init__(self, numVariables):
        self.velocities = []
        self.positions = []
        self.pBest = []
        for i in range(0, numVariables):
            self.velocities.append(random.random())
            self.positions.append(random.random())
            self.pBest.append(float('inf'))
Alexandre Senges
  • 1,474
  • 1
  • 13
  • 22