ten small Python programs

Steve Howell showell30 at yahoo.com
Sat May 26 21:48:45 EDT 2007


--- Paul McGuire <ptmcg at austin.rr.com> wrote:

> I ***love*** this "10 Little Programs" idea!  As
> soon as I get a
> breathing space, I'm going to add a "10 Little
> Parsers" page to the
> pyparsing wiki!
>

Thanks. :)

I'm thinking you could actually have a progression
from a 1 line program up to a 50-line program.  The
number 50 is kind of arbitrary, but my gut says that
by a 50-line program, you will have demonstrated
almost every useful concept.

 
> 
> >
> > >     class ShoppingCart:
> > >         def __init__(self): self.items = []
> > >         def buy(self, item):
> self.items.append(item)
> > >         def boughtItems(self): return self.items
> > >     myCart = ShoppingCart()
> > >     myCart.buy('apple')
> > >     myCart.buy('banana')
> > >     print myCart.boughtItems()
> 
> If you want to nitpick, I'd rather go after the
> one-liner methods with
> the body on the same line as the def statement.
> 

Agreed.  I didn't like that either.

> How's this for a better non-trivial method example:
> 
>     MAX_ITEMS_FOR_EXPRESS_LANE = 10
>     def canUseExpressLane(self):
>         return (len(self.items) <=
> MAX_ITEMS_FOR_EXPRESS_LANE)
> 
> or call it "can_use_express_lane" if you must.
> 

Yep, that sounds more in the ballpark of what I'd want
to show, versus a weakish class that just encapulates
a list.

Here's my challenge to whoever wants to take it--write
(or find) a program with 20 or fewer lines that
sufficiently motivates the need for classes, has
decent Python style, and is newbie friendly.

The tutorial has this example, which is useful for
demonstrating the syntax of classes, but it doesn't
actually do anything interesting:

class MyClass:
    "A simple example class"
    i = 12345
    def f(self):
        return 'hello world'

It also has a ComplexNumber class, but I don't want to
scare away mathphobes.

It does have this idiom, which I think is worth
putting somewhere into the progression.

class Employee:
    pass

john = Employee() # Create an empty employee record

# Fill the fields of the record
john.name = 'John Doe'
john.dept = 'computer lab'
john.salary = 1000





       
____________________________________________________________________________________Take the Internet to Go: Yahoo!Go puts the Internet in your pocket: mail, news, photos & more. 
http://mobile.yahoo.com/go?refer=1GNXIC



More information about the Python-list mailing list