Behavior of mutable class variables

T

tkpmep

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 = 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 != '':
Stock.NStocks.append(1)

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

elif retHist != '':
Stock.NStocks +=1


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

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)
 
D

Diez B. Roggisch

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/general.html#why-are-default-values-shared-between-objects

Diez
 
T

tkpmep

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 != '':
Stock.NStocks.append(1)

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

elif retHist != '':
Stock.NStocks +=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, returnHistoryDir[idList] )

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

Terry Reedy

| 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
 
T

tkpmep

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, returnHistoryDir[idList] )

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

tkpmep

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.
 
C

castironpi

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,979
Messages
2,570,185
Members
46,727
Latest member
FelicaTole

Latest Threads

Top