[Tutor] OOPs?

alan.gauld@bt.com alan.gauld@bt.com
Fri, 29 Mar 2002 18:31:45 -0000


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

[ This is an idiom I've never seen in OOP beginners in 
  C++ or Java or Smalltalk but this is at least the 3rd 
  time its happened on this list - wierd!]

The easiest way to have named objects is probanbly to create 
a dictionary and store them there indexed by the name:

stocks = {}
newstock = raw_input("Enter name of new stock: ")
stocks[newstock] = Stock()

later...

stocks["IBM"].update()

> the instance of the class.  And, if I want a list of all my 
> stocks, I'd just call Stock.stocklist.

You can do that by making the class contain a list of objects 
and make the init method add self to that list. Or use

stocks.keys() to return the list of names...

> with functions, dictionaries and lists without using a class, but I'm 
> trying to understand classes.  Any suggestions or insights?

I can see why you migt do this but personally I'd usually 
include the name as an attribute of the class and as a 
parameter of the constructor(init). Then you can iterate 
over your stocks asking them their names. It seems like 
only occasionally (in this app) would you index by company 
name - but if you think you do that a lot then a dictionary 
is the sensible option.

Alan g.
Author of the 'Learning to Program' web site
http://www.freenetpages.co.uk/hp/alan.gauld