I forgot to wind up my example .... ; (

Dave Rose photos at conversent.net
Fri Apr 29 18:37:13 EDT 2005


So, I forgot the last part of my example that might gel in your mind why 
Objects are useful in certain situations.  Ok so you maybe followed my example 
of the shopping cart.  Let's just forget for a moment the use for shopping 
carts is for  websites.  Let's just say you were going to write the lines 
directly into Python, like maybe at the IDLE interpreter.  Like maybe you're 
testing the functionality of the routine for correctness, not actual 
implementation.

You have a ShoppingCartClass(), and three users-> Dave, Tommy, Bryan.
ShoppngCartClass() has 3 methods:
.AddItem()
.RemoveItem()
.CheckOut()

These are really just 'def' routintes you write in the class to do some action 
or calculation.  Here, we want to either add an item to 'the cart', remove 
one, or finalize the order. 

In the interpreter,  you could do this. Define 3 users of the 
ShoppingCartClass.

Dave = ShoppingCartClass()
Tommy = ShoppingCartClass()
Bryan = ShoppingCartClass()


Ok.  Now you could do different things to each:

Dave.AddItem(sku=5)
Tommy.AddItem(sku=77)
Tommy.AddItem(sku=12)
Tommy.RemoveItem(sku=12)
Dave.CheckOut(state=CT, ccard='visa', ccardnum='1234-5678-8765-431')
Tommy.CheckOut(stsate=RI, ccard='mastercard', ccardnum='431-123-4321-1234')
Bryan.CancelOrder()

so, if you were then to take account of what you had, you'd know:
Dave has item SKU=5
Tommy has item SKU=77
Bryan has his order cancelled.

This is still very hard-coded.  You could abstract, or maybe variablize, 
things more. Let's try:

You can mix classes with say dictionaries, to make their use in routines more 
beneficial.

So, you could have:

user = “Dave”
ShoppingCart={}
ShoppingCart[user] = ShoppingCartClass()
user = “Tommy”
ShoppingCart[user] = ShoppingCartClass()
user = “Dave”
ShoppingCart[user].AddItem(sku=55)
user = “Tommy”
ShoppingCart[user].CheckOut( ... )
ShoppingCart[“Dave”].CheckOut( ... )

Putting the classes in the dictionary allow you to use names from things like 
fields, config files, text files, TextControls in my favorite program 
wxPython, etc.

If you can wrap your mind around this, you're well on your way to using OOP I 
believe.  If not, , don't give up. I'm just a python/programming newbie and 
maybe missed the boat completely with my posting.

-Dave 




More information about the Python-list mailing list