Behavior of mutable class variables

tkpmep at hotmail.com tkpmep at hotmail.com
Wed May 9 17:25:18 EDT 2007


To test some theories, I created a new class variable, an int named
N1, which is not mutable. So my Stock class now looks as follows:

class Stock(object):
    NStocks = []             #Class variables
    N1         = 0


    def __init__(self, id, returnHistory):
        self.id = id
        self.retHist = returnHistory

        Stock.N1 += 1
        for i in range(len(returnHistory)):
            if len(Stock.NStocks) <= i   and retHist[i] != '':
                Stock.NStocks.append(1)

            elif len(Stock.NStocks) <= i and retHist[i] == '':
                Stock.NStocks.append(0)

            elif retHist[i] != '':
                Stock.NStocks[i] +=1

I expect Stock.N1 to reset to zero at each call to simulation(), but
it does not - it keeps incrementing!
I then added a line to simulation( ) that deletes all the stocks at
the end of each simulation (see below). You guessed it - no change!
NStocks and N1 keep increasing! At this point I am thoroughly
mystified. What gives?

def simulation(N, par1, par2, idList, returnHistoryDir):
    port = []
    for i in range(N):
        port.append( Stock(idList[i], returnHistoryDir[idList[i]] )

    del port[:]
    results = ......
    print results.






More information about the Python-list mailing list