help with my first use of a class

BartlebyScrivener rpdooling at gmail.com
Fri Oct 20 02:00:03 EDT 2006


I am a mere hobbyist. Spent several hours trying to make a class,
because I think this is an occasion where I need one. But I can't make
it work.

This code "works" (only because of the global c, which I know I'm
supposed to avoid, by using a Class). I edited the rest to leave out
the irrelevant formatting and printing of the quotations.

I've read about Classes several times, but I don't "get" them yet.
Obviously. If I can solve one real life problem like this, then maybe
I'll see the light.

If I understand the power of Classes correctly, I could make one that
would allow me to make a new instance that would connect to, say, an
SQLite3 db instead of the Access db, as well as to create more methods
that will do different SQL searches.

Thank you for any help,

rd

--------------------------------------

import mx.ODBC.Windows as odbc
import sys
import random

def connect():
    global c
    db='DSN=Quotations'
    conn = odbc.DriverConnect(db)
    c = conn.cursor()

def random_quote():
    """
    Counts all of the quotes in MS Access database Quotations2005.mdb.
    Picks one quote at random and displays it using textwrap.
    """
    c.execute ("SELECT COUNT(Quote) FROM PythonQuoteQuery")
    # Yields the number of rows with something in the quote field
    total_quotes = c.fetchone()
    # Get a random number somewhere between 1 and the number of total
quotes
    quote_number = (random.randint(1, total_quotes[0]),)
    # Select a quote where the ID matches that number
    c.execute ("SELECT Author, Quote FROM PythonQuoteQuery WHERE ID=?",
quote_number)
    quote = c.fetchone()
    blah blah blah

def print_quote()
    code to format and print the quote (which will also have to be
global, unless I learn Classes!)


if __name__ == '__main__':
    if len(sys.argv) == 1:
        connect()
        random_quote()
        print_quote()




More information about the Python-list mailing list