Python : How to create a dynamic list of class values

Viewed 2921

I have tried to find the anwser to that question, but I cannot find the good Keywords ...

I want to know how can I create a list of value help in instances of a class. What I do not want is that :

class Test:
    def __init__(self,i)
        self.i = i

inst1 = Test(2)
inst2 = Test(5)

MyList = [inst1.i,inst2.i]

At that point MyList = [2,5] if I change the value if inst1

inst1.i = 4
print MyList 
[2,5]

MyList is STILL [2,5] but I want it to be updated to [4,5]

print MyList
[4,5]

So my question is that, how do I create a list that points to the variable and not the variable value ?

If you want to know why : I am running a MonteCarlo simulation in which I have a lot of proteins, each with one energy value, and each Protein is instantiated from a Protein class.

class Protein:
    def __init__(self,sequence,energy):
        self.sequence = sequence
        self.energy = energy

That energy value of some proteins gets updated during a montecarlo simulation. I need a list of all the energies to perform some calculation on the distribution. Right know, I updated the list with a for loop, but it would be way more efficient if I could have a list that points to the variable, that way every time an energy in the Protein class is changed the list is updated automatically.

Thanks a lot !

5 Answers
Related