[Tutor] OOPs?

Seabrook, Richard rhseabrook@mail.aacc.cc.md.us
Fri, 29 Mar 2002 09:50:49 -0500


-----Original Message-----
From: Bryce Embry

  Can anyone give me an idea of where my understanding has gone
off 
track, or how to make this concept work?

I have made a class that looks like the following:

class Stock:
         stocklist = []
         def __init__(self, name, price, shares):
                 # get name of stock, initial price, initial number of
shares
                 # stick the new stock name in Stock.stocklist
         def update (self, newprice, newshares):
                 # change the shares in a stock
         def otherstuff(self):
                 # do other stuff, like print current value, etc.

My thought was to design the program so that each time the user added a 
stock to the portfolio, the program would create a new instance of the 
class.  I don't know how to do that, though.  I want what in PHP is a 
"variable variable", where I can do something like this:

newstock = raw_input("Enter name of new stock: ")
newstock = Stock()

So, if the person chose IBM, I would have an instance called 
IBM.Stock().  If he typed in RHAT, I'd have another instance called 
RHAT.Stock().   Then, I could update, track, and do other stuff by
calling 
the instance of the class.  And, if I want a list of all my stocks, I'd 
just call Stock.stocklist  .

Is this even the right way to use a class?  I know I could get the job
done 
with functions, dictionaries and lists without using a class, but I'm 
trying to understand classes.  Any suggestions or insights?
====================================================================

Well, it is one way, but why should a stock contain a list of anything,
except perhaps its own price history, and other data about that particular
stock.  It seems to me that, rather a stock-list should contain an instance
of a stock, and that you'd most often want to process the stock-list to
create or find out about particular stocks.  Think about two classes:

class Stocklist:
   def __init__(self):
      self.theList=[]
   def addStock(self,stk):
      self.theList.append(stk)
   etc.

Then you can create a new stock and give it to the stocklist to store away,
like this

name = raw_input("What is the name of the new stock?")
stock = Stock(name)  (You'll have to change your Stock constructor)
stocklist = Stocklist()
stocklist.addStock(stock)

In this way, instances of Stock are maintained by an instance of Stocklist.
Remember to use the 'self' reference in a class definition to create and
store data in the instance.
Dick S.
=====================================================================