Simple question - stock market simulation

Robert Kern robert.kern at
Tue Feb 10 00:26:09 CET 2009

On 2009-02-09 17:10, cptn.spoon wrote:
> On Feb 9, 6:48 pm, "Hendrik van Rooyen"<m... at>  wrote:
>> "cptn.spoon"<cp...... at>  wrote:
>> On Feb 9, 3:58 pm, Paul Rubin<http://phr...@NOSPAM.invalid>  wrote:
>>> Thanks Paul! I thought this might be the case. So how would I get the
>>> StockMarket class instance to contain many Stock class instances and
>>> then be able to iterate through them? I'm guessing the basic structure
>>> would be as follows...but I think I'm wrong:
>>> class StockMarket:
>>>   pass
>> No.
>> At this level, just use a list of instances of your Stock class.
>> - Hendrik
> How do I get a list of instances of a particular class? Is there a way
> to do this dynamically?

You *can*, but I highly recommend that you don't. Instead, just keep your own 
list of instances. When you make a new instance, just append it to the list (see 

   all_stocks = []

> Also, what would be the way of dynamically creating an instance of a
> class based on user input (ie a user wants to create a new instance of
> the Stock class via shell input)?

Define an __init__ method on your class to initialize it from given values. Use 
raw_input() to query the user for information. Convert the text input to 
whatever objects your class needs (e.g. if the user entered "10" on the prompt, 
x=raw_input() will return the string '10', so you would do int(x) to get the 
integer 10). Now, instantiate your class with the arguments:

   the_stock = Stock(name, risk, initial_price)

And append it to your list of stocks.


Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
  that is made terrible by our own mad attempt to interpret it as though it had
  an underlying truth."
   -- Umberto Eco

More information about the Python-list mailing list