Home > Software design >  Class objects stored in numpy.array() not working properly
Class objects stored in numpy.array() not working properly

Time:11-03

I am trying to create an array of objects for the class value. But the values of all the objects become equal.

import numpy as np

class value:
  def store(self,jobid,deadline,profit):
    self.job = jobid
    self.deadline = deadline
    self.profit = profit

  def initialize(self):
    job = input()
    deadline = int(input())
    profit= int(input())
    self.store(job,deadline,profit)


def disp(arr,n):
  for i in range(n):
    print(str(arr[i].job) " " str(arr[i].deadline) " " str(arr[i].profit))


n=2
arr = np.array([None for i in range(n)])
val = value()

for i in range(n):
  val.initialize()
  arr[i]=val

disp(arr,n)

Input

A
2
3
B
2
1

Expected output
A 2 3
B 2 1

Output I am getting
B 2 1
B 2 1

What am I be doing wrong and what might fix it?

CodePudding user response:

You are creating only one instance of your class with the initial call to value(). Calls to initialize and store just modify the content of that instance.

You then assign the same instance to all array elements.

To fix this, you need to create new instances by putting the val = value() inside the loop.

  • Related