473,657 Members | 2,523 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

help with my first use of a class

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=Quotati ons'
conn = odbc.DriverConn ect(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 PythonQuoteQuer y")
# 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 PythonQuoteQuer y 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()

Oct 20 '06 #1
16 1351
Whoah. At least I got the connection. I think. Maybe I can figure more
on my own. Any help appreciated.

Thanks

---------

class Connection:
def __init__(self, aDatasource):
self.db = aDatasource
self.conn = odbc.DriverConn ect(self.db)
self.conn.curso r()

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 = Connection('DSN =Quotations')
c.execute ("SELECT COUNT(Quote) FROM PythonQuoteQuer y")

Oct 20 '06 #2
BartlebyScriven er wrote:
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
This means you want to use a global variable c which doesn't exist yet,
an example would be to save this code to a file:

#!/usr/bin/env python

c = 0
def test_global():
global c
c = 1

print c

this will print 0 when you run it
db='DSN=Quotati ons'
conn = odbc.DriverConn ect(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 PythonQuoteQuer y")
# 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 PythonQuoteQuer y 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!)

A class structure could look like - please bear in mind that I don't
know mx.ODBC.Windows - I guess it is not completely DB-API compliant,
as you don't use a connect method.

class SQLQuery(object ):
"""Object which connects to the database and can execurte SQL
commands
"""
def __init__(self, conn):
"""conn is a dictionary {'serverId': XX, 'userId': YY,
'passWord': ZZ}
"""
self.connection = connect(conn['userId'], conn['passWord'],
conn['serverId'])
self.cursor = self.__connecti on.cursor()

def select(self, selectqry):
"""argument selectqry specifies a sql which returns data, like a
select
"""
self.cursor.exe cute(selectqry)
return self.cursor.fet chall()

sql = SQLQuery('serve rId': 'XX', 'userId': 'YY', 'passWord': 'ZZ')
qoutes = sql.select("SEL ECT COUNT(Quote) FROM PythonQuoteQuer y")
print quotes
if __name__ == '__main__':
if len(sys.argv) == 1:
sys.argv is a list, where the first argument is the name of the running
script, the second element is the first argument, etc.
connect()
random_quote()
print_quote()
Oct 20 '06 #3
BartlebyScriven er wrote:
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=Quotati ons'
conn = odbc.DriverConn ect(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 PythonQuoteQuer y")
# 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 PythonQuoteQuer y 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()
You really don't need classes for this, just parameters + return values.
Probably best would be to master the idea of parameters + return values
before yo move on to classes. This is called "procedural " programming.
Notice that there is no name collision because of strict python
namespaces (a good idea, according to Tim Peters).
For example:

def connect():
db='DSN=Quotati ons'
conn = odbc.DriverConn ect(db)
c = conn.cursor()
# NOTE THE RETURN VALUE:
return c

def random_quote(c) : # <== NOTE THE PARAMETER
"""
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 PythonQuoteQuer y")
# Yields the number of rows with something in the quote field
total_quotes = c.fetchone()
# Get a random number somewhere between 1 and ...
quote_number = (random.randint (1, total_quotes[0]),)
# Select a quote where the ID matches that number
q = "SELECT Author, Quote FROM PythonQuoteQuer y WHERE ID=?"
c.execute (q, quote_number)
quote = c.fetchone()
# NOTE THE RETURN VALUE:
return quote

def print_quote(quo te): # <== NOTE THE PARAMETER
print quote # <== WHATEVER YOU WANT TO DO

if __name__ == '__main__':
if len(sys.argv) == 1:
c = connect() # <== NO COLLISION: NAMESPACES
quote = random_quote(c) # <== DITTO
print_quote(quo te) # THERE YOU HAVE IT
James
Oct 20 '06 #4
Wow,

That's great, James.

Thanks. I shall put it together.

Appreciate it.

rd

Oct 20 '06 #5
BartlebyScriven er wrote:
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.
Think of a class as both a "blueprint" for objects and a factory
creating these objects. The class lets you define the attributes and
behaviors of it's instances.
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,
import mx.ODBC.Windows as odbc
import sys
import random

def connect():
global c
db='DSN=Quotati ons'
conn = odbc.DriverConn ect(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 PythonQuoteQuer y")
# 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 PythonQuoteQuer y 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!)
Ever wondered what arguments and return values were for ?-)
if __name__ == '__main__':
if len(sys.argv) == 1:
connect()
random_quote()
print_quote()
First, notice that you *don't* need a class here to avoid globals.
Learning to use function as *functions* (ie: taking arguments and
returning values) instead of procedure would help:

def random_quote(cu rsor):
c.execute ("SELECT COUNT(Quote) FROM PythonQuoteQuer y")
total_quotes = c.fetchone()
quote_number = (random.randint (1, total_quotes[0]),)
c.execute (
"SELECT Author, Quote FROM PythonQuoteQuer y WHERE ID=?",
quote_number
)
return c.fetchone()

def format_quote(qu ote):
# code here
return formatted_quote

def main(*args):
if len(args) < 2:
print >sys.stderr, "Missing dsn arg\nusage : %s dsn" % args[0]
return 1
dsn = args[1]
try:
conn = odbc.DriverConn ect(dsn)
except <SomeODBCErrorH ere>, e:
print >sys.stderr "Cannot connect to %s : %s" % (dsn, e)
return 1
quote = random_quote(co nn.cursor())
print format_quote(qu ote)
conn.close()
return 0

if __name__ == '__main__':
sys.exit(main(* sys.argv))
Now for an OO version - that won't buy you much IMHO:

class SQLFortune(obje ct):
def __init__(self, dsn):
self._dsn = dsn
self._cnx = None

@apply
def connection():
def fget(self):
if self._cnx is None:
self._cnx = odbc.DriverConn ect(self.dsn)
return self._cnx
def fset(self, _):
raise AttributeError( "Attribute is read-only")
return property(**loca ls())

def random_quote(se lf):
c = self.connection .cursor()
c.execute ("SELECT COUNT(Quote) FROM PythonQuoteQuer y")
total_quotes = c.fetchone()
quote_number = (random.randint (1, total_quotes[0]),)
c.execute (
"SELECT Author, Quote FROM PythonQuoteQuer y WHERE ID=?",
quote_number
)
return c.fetchone()

def format_quote(se lf, quote):
# code here
return formatted_quote

def close(self):
try: self._cnx.close ()
except: pass

def main(*args):
if len(args) < 2:
print >sys.stderr, "Missing dsn arg\nusage : %s dsn" % args[0]
return 1
dsn = args[1]
fortune = SQLFortune(dsn)
print fortune.format_ quote(fortune.r andom_quote())
fortune.close()
return 0

if __name__ == '__main__':
sys.exit(main(* sys.argv))
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom. gro'.split('@')])"
Oct 20 '06 #6
BartlebyScriven er wrote:
Whoah. At least I got the connection. I think. Maybe I can figure more
on my own. Any help appreciated.

Thanks

---------

class Connection:
def __init__(self, aDatasource):
self.db = aDatasource
self.conn = odbc.DriverConn ect(self.db)
self.conn.curso r()
This creates a cursor, that's immediatly discarded.
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 = Connection('DSN =Quotations')
c.execute ("SELECT COUNT(Quote) FROM PythonQuoteQuer y")
And this will raise an AttributeError, since your (mostly useless)
Connection class doesn't define an 'execute' method.

--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom. gro'.split('@')])"
Oct 20 '06 #7
Bruno Desthuilliers wrote:
First, notice that you *don't* need a class here to avoid globals.
Learning to use function as *functions* (ie: taking arguments and
returning values) instead of procedure would help:

def random_quote(cu rsor):
c.execute ("SELECT COUNT(Quote) FROM PythonQuoteQuer y")
make that "cursor.execute " (etc)

</F>

Oct 20 '06 #8
Fredrik Lundh wrote:
Bruno Desthuilliers wrote:
>First, notice that you *don't* need a class here to avoid globals.
Learning to use function as *functions* (ie: taking arguments and
returning values) instead of procedure would help:

def random_quote(cu rsor):
c.execute ("SELECT COUNT(Quote) FROM PythonQuoteQuer y")

make that "cursor.execute " (etc)
oops, sorry - not enough coffein, I guess.
Thanks for the correction.

--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom. gro'.split('@')])"
Oct 20 '06 #9
Thanks, Bruno. Very educational.

rd

Bruno Desthuilliers wrote:
Think of a class as both a "blueprint" for objects and a factory
creating these objects. The class lets you define the attributes and
behaviors of it's instances.

First, notice that you *don't* need a class here to avoid globals.
Learning to use function as *functions* (ie: taking arguments and
returning values) instead of procedure would help:

Now for an OO version - that won't buy you much IMHO:
Oct 20 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
2032
by: dinks | last post by:
Hi, I'm new to C++ and have been assigned a task which i dont completely understand. Any help would be greately appreciated. Here is the problem: The class "linkedListType" use the "assert" facility. I am to get rid of them and replace them with exceptions. I need to create a "linkedListException" class that's declared and implemented in my "linkedListType" class. This class needs to inherit from the base "exception" class and return...
7
1802
by: Christian Christmann | last post by:
Hi, in the past I always appreciated your help and hope that you also can help me this time. I've spent many many hours but still can't solve the problem by myself and you are my last hope. I've a program which is using self-written double-linked lists as a data structure. The template list consists of list elements and the list itself linking the list elements.
5
2985
by: Craig Keightley | last post by:
Please help, i have attached my page which worksin IE but i cannnot get the drop down menu to fucntion in firefox. Any one have any ideas why? Many Thanks Craig <<<<<<<<<<<<<<CODE>>>>>>>>>>>>>>>> <html>
0
1485
by: Shaggyh | last post by:
hi im needing help with a program im writing to do subnetting i was on before about it and i got some help. the code below wont work for me and i cant think of why not. i was wondering if anyone out there can help, even come up with a better way of doing this.. i have 2 files.. here is my first file.. // a library assembly i.e. dll
1
3705
by: Rahul | last post by:
Hi Everybody I have some problem in my script. please help me. This is script file. I have one *.inq file. I want run this script in XML files. But this script errors shows . If u want i am attach this script files and inq files. I cant understand this error. Please suggest me. You can talk with my yahoo id b_sahoo1@yahoo.com. Now i am online. Plz....Plz..Plz...
0
5557
by: gunimpi | last post by:
http://www.vbforums.com/showthread.php?p=2745431#post2745431 ******************************************************** VB6 OR VBA & Webbrowser DOM Tiny $50 Mini Project Programmer help wanted ******************************************************** For this teeny job, please refer to: http://feeds.reddit.com/feed/8fu/?o=25
10
2103
by: CuTe_Engineer | last post by:
hii, i have cs assignment i tried to solve it but i still have many errors , plzz help mee :"< it`s not cheating becuz i`ve tried & wrote the prog. i just wanna you to show me my mistakes #these are the operations + = , - = , * = , 1/ = only if 0 not in .
16
2768
by: gnawz | last post by:
I have a pagination function I am using in a file called functions.php as below<? //Pagination functions function getPagingQuery($sql, $itemPerPage = 10) { if (isset($_GET) && (int)$_GET > 0) { $page = (int)$_GET; } else { $page = 1; } // start fetching from this row number $offset = ($page - 1) * $itemPerPage; return $sql . " LIMIT $offset, $itemPerPage"; } /* Get the links to navigate between...
3
2206
by: ibeehbk | last post by:
Hi. I have a form made in xhtml. I test via vbscript to make sure none of the fields are empty and properly formatted (ie email). All the regular fields work. However, I have two drop down menus that are SELECT elements (javascript-- one named arrivalcity and one named returncity). Basically they ask for a departure and return city and another menu appears with options based on that city. I can't seem to get the input from these fields in the...
2
10023
by: hcaptech | last post by:
This is my Test.can you help me ? 1.Which of the following statement about C# varialble is incorrect ? A.A variable is a computer memory location identified by a unique name B.A variable's name is used to access and read the value stored in it C.A variable is allocated or deallocated in memory during runtime D.A variable can be initialized at the time of its creation or later 2. The.……types feature facilitates the definition of classes...
0
8392
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8305
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8726
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8503
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8603
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7320
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6163
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
2
1944
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1604
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.