473,396 Members | 1,815 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

Behavior of mutable class variables

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
6 1385
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
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

<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
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
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
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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

49
by: Mark Hahn | last post by:
As we are addressing the "warts" in Python to be fixed in Prothon, we have come upon the mutable default parameter problem. For those unfamiliar with the problem, it can be seen in this Prothon...
50
by: Dan Perl | last post by:
There is something with initializing mutable class attributes that I am struggling with. I'll use an example to explain: class Father: attr1=None # this is OK attr2= # this is wrong...
3
by: Thomas Matthews | last post by:
Hi, I understand that a member function can be declared as const {meaning it doesn't alter the member variables), but can it be declared as mutable? I have class that stores its members into...
4
by: DaKoadMunky | last post by:
<CODE> #include <iostream> using namespace std; int Foo(int x,int y) { int result = x; result*=y; result+=y;
6
by: Samuel M. Smith | last post by:
I have been playing around with a subclass of dict wrt a recipe for setting dict items using attribute syntax. The dict class has some read only attributes that generate an exception if I try to...
12
by: Vincent RICHOMME | last post by:
Hi, I am currently implementing some basic classes from .NET into modern C++. And I would like to know if someone would know a non mutable string class.
3
by: Sambo | last post by:
By accident I assigned int to a class member 'count' which was initialized to (empty) string and had no error till I tried to use it as string, obviously. Why was there no error on assignment( near...
4
by: Muthu Arumugam | last post by:
Tried the following c# code static void Main(string args) { ArrayList list = new ArrayList(); int i = 10;
35
by: bukzor | last post by:
I've found some bizzare behavior when using mutable values (lists, dicts, etc) as the default argument of a function. I want to get the community's feedback on this. It's easiest to explain with...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.