By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,965 Members | 1,690 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,965 IT Pros & Developers. It's quick & easy.

Behavior of mutable class variables

P: n/a
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)

May 9 '07 #1
Share this Question
Share on Google+
6 Replies


P: n/a
tk****@hotmail.com schrieb:
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()
http://www.python.org/doc/faq/genera...etween-objects

Diez
May 9 '07 #2

P: n/a
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.

May 9 '07 #3

P: n/a

<tk****@hotmail.comwrote in message
news:11*********************@w5g2000hsg.googlegrou ps.com...
| 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,

Why would you expect that ;-)
A class statement is usually executed exactly once, as in your code.
The body of a class statement usually consists of several name bindings:
some are explicit, like your NStocks assignment statement;
some are implicit, like you __init__ function definition.
The resulting dictionary is used to create the class object, which is
mostly a wrapper around the dict created by the class statement body.

tjr

May 9 '07 #4

P: n/a
On May 9, 5:25 pm, tkp...@hotmail.com wrote:
To test some theories, I created a new class variable, an int named
Diez,

Thanks. It is for precisely this reason that I added another class
variable - the immutable int N1. But this too keeps getting
incremented on subsequent calls to simulation( ). I also tried setting
the class variable N1 to 0 at the end of the simulation and also
deleting all the stocks in port (see below). Nothing works - and I
don't understand why.

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

p[0].NStocks = 0
del port[:]
results = ......
print results.

May 9 '07 #5

P: n/a
Thanks for the insights. I solved the problem as follows: I created a
new class method called cleanUp, which resets NStocks to an empty list
and N1 to 0. Works like a charm - it's the first time I've used a
class method, and I immediately see its utility. Thanks again

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

@classmethod
def cleanUp(cls):
Stocks.NStocks = []
Stocks.N1 = 0

def simulation(N, par1, par2, idList, returnHistoryDir):

Stock.cleanUp()
results = ......
print results.

May 9 '07 #6

P: n/a
On May 9, 5:49 pm, tkp...@hotmail.com wrote:
Thanks for the insights. I solved the problem as follows: I created a
new class method called cleanUp, which resets NStocks to an empty list
and N1 to 0. Works like a charm - it's the first time I've used a
class method, and I immediately see its utility. Thanks again

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

@classmethod
def cleanUp(cls):
Stocks.NStocks = []
Stocks.N1 = 0

def simulation(N, par1, par2, idList, returnHistoryDir):

Stock.cleanUp()
results = ......
print results.
class A:
b= 0

A.b
a= A()
a.b
a.b+= 1
a.b
A.b
A.b=20
a.b
A.b
a1= A()
a1.b
a.b
A.b
a1.b+=10
a1.b
a.b
A.b

It looks like an instance gets its own copy of A's dictionary upon
creation, and -can- no longer affect A's dictionary, though both can
be changed elsewhere.

Doesn't seem prudent to -obscure- a class by an instance, but if
that's not what goes on, then I'm missing something.

May 9 '07 #7

This discussion thread is closed

Replies have been disabled for this discussion.