Behavior of mutable class variables

tkpmep at hotmail.com tkpmep at hotmail.com
Wed May 9 16:57:37 EDT 2007


I have written a program that runs portfolio simulations with
different parameters and prints the output, but am mystified by the
behavior of a mutable class variable. A simplified version of the
program follows - would you kindly help me understand why it behaves
the way it does.

The function main() reads some data and then repeatedly calls
simulation() with different parameter values. Each time the simulation
runs, it creates a collection of stocks, simulates their behavior and
prints the results.

Here's what I expect to happen each time simulation( ) is called: the
class variable NStocks for the class Stock is initialized to an empty
list, and is then built up by __init__ as stocks are added to the
portfolio. Unfortunately, ths is not what actuallly happens .NStocks
is initialized to an empty list and then built up as I expect on the
first call to simulation( ), but appears to persists between calls to
simulation( ).

Question: Why? Do I not create an entirely new list of stock objects
each time I enter simulation()? I am aware that mutable items can
behave in tricky ways, but am thoroughly mystified by the persistence
of NStocks between calls to simulation()

Sincerely

Thomas Philips

class Stock(object):
    NStocks = []             #Class variable, NStocks[i] = number of
valid stocks at time i

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

       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


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

    results = ......
    print results.


def main():
   N, idList, returnHistoryDir= readData()
   for par1 in range(10):
        for par2 in range(10):
            simulation(N, par1, par2, idList, returnHistoryDir)




More information about the Python-list mailing list