2

When I run this code, all x1 attributes are initialized with the same generated random number. for example, all set to 2!!!

@dataclass
class Position:
    x1: int = 0
    x2: int = 0

@dataclass
class Particle:
    position: Position
    pbest: Position 
    velocity: Position
    f : float = 0.0

def initialize():
    particles=np.full(20,Particle(Position(),Position(),Position()))
    
    for p in particles:
        p.position.x1=random.randint(-5,5)

mSafdel
  • 1,527
  • 4
  • 15
  • 25

1 Answers1

1

You created a single instance of Particle, then created an array with 20 references to that object. Every time you change p.position.x1, you are updating that single object, regardless of which reference to the object you start with.

Instead, do something like

particles = np.array(Particle(Position(x1=random.randint(-5, 5)), Position(), Position()) for _ in range(20))
chepner
  • 497,756
  • 71
  • 530
  • 681