0

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?

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.