Nova Trauben
Nova Trauben

Reputation: 47

dynamic instances of a class object overwriting each other

I have a simple class that stores simple data. The class is as follows.

class DataFormater:

    def __init__(self, N, P, K, price):

       self.N = N
       self.P = P
       self.K = K
       self.price = price

The code that calls this class is

from DataFormater import DataFormater

#global variables
ObjectList = [0,1,2,3,4,5,6,7,8,9,10,
              11,12,13,14,15,16,17,18,19,20,
              21,22,23,24,25,26,27,28,29,30,
              31,32,33,34,35,36,37,38,39,40,
              41,42,43,44,45,46,47,48,49,50]
ObjectListCounter = 0

# main
print "enter you N-P-K values, followed by a coma, then the price"
print "example ---->  5 5 5 %50 "
print "return as many values as you want to sort, then enter, 'done!' when done."

while True:
    RawData = raw_input()
    if RawData == 'done!':
        break

    else:

        ObjectList[ObjectListCounter] = DataFormater
        ObjectList[ObjectListCounter].N = int(RawData[0])  
        # very simple test way of putting first indice in ObjectList[ObjectListCounter].N
        ObjectListCounter += 1

print ObjectList[0].N
print ObjectList[1].N

My idea is that ObjectList[0] would create that object '1' that I could call with 1.N

But, when I call these, it seems that I have overwritten the previous instances.

this is what prints...

return as many values as you want to sort, then enter, 'done!' when done.
12
1
done!
1
1

Thanks so much! And I know that my post is messy, I don't exactly know how to make it more "pretty"

Upvotes: 2

Views: 106

Answers (1)

MrName
MrName

Reputation: 2529

So, it looks like you are assigning the actual class (instead of an instance of the class) in your loop. Where you do this:

ObjectList[ObjectListCounter] = DataFormater

I think what you actually want is this

ObjectList[ObjectListCounter] = DataFormater(...insert args here....)

EDIT to address the comments:

Your class init method looks like this:

def __init__(self, N, P, K, price):

That means that to create an instance of your class, it would look like this:

my_formater = DataFormater(1, 2, 3, 4)

You would then be able to access my_formater.N which would have a value of 1.

What you are trying to do instead is access a CLASS level attribute, DataFormater.N. This is generally used in situations where you have a constant variable that does not change between instances of the class. For example:

class DataFormater():

    CONSTANT_THING = 'my thing that is always the same for every instance'

You would then be able to access that variable directly from the class, like this:

DataFormater.CONSTANT_THING

I hope that clears things up.

Upvotes: 3

Related Questions