帮助我第一次使用课程 [英] help with my first use of a class

查看:82
本文介绍了帮助我第一次使用课程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是一个业余爱好者。花了几个小时试图上课,

,因为我认为这是一个我需要的场合。但是我不能让它工作。


这段代码工作 (仅仅是因为全局c,我知道我应该通过使用类来避免
)。我编辑了其余部分,遗漏了

无关的格式和打印报价。


我已多次阅读过类,但我不知道't得到他们呢。

显然。如果我能解决这样一个现实生活中的问题,那么也许

我会看到光。


如果我正确理解了类的强大功能,我可以制作一个

允许我创建一个新实例,它可以连接到一个

SQLite3数据库而不是Access数据库,以及创建更多方法

将执行不同的SQL搜索。


感谢您的帮助,


rd


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


导入mx.ODBC.Windows为odbc

导入系统

随机导入


def connect():

global c

db =''DSN = Quotations''

conn = odbc.DriverConnect(db)

c = conn.cursor()

def random_quote():

"""

计算MS Access数据库Quotations2005.mdb中的所有引号。

随机选取一个引号并使用textwrap显示它。

& quot;""

c.execute(" SELECT COUNT(Quote)FROM PythonQuoteQuery")

#在quote字段中产生带有内容的行数< br $>
total_quotes = c.fetchone()

#获取一个介于1和总数之间的随机数

报价

quote_number =(random.randint(1,total_quotes [0]),)

#选择ID与该数字匹配的报价

c.execute(" SELECT作者,引用来自PythonQuoteQuery WHERE ID =?",

quote_number)

quote = c.fetchone()

blah blah blah < br $>

def print_quote()

代码格式化和打印报价(除非我学习,否则全局也必须是b
类!)

if __name__ ==''__ main__'':

if len(sys.argv)== 1:

connect( )

random_quote()

print_quote()

解决方案

哇。至少我得到了连接。我认为。也许我自己可以想象更多

。任何帮助表示赞赏。


谢谢


---------


class Connection:

def __init __(self,aDatasource):

self.db = aDatasource

self.conn = odbc.DriverConnect(self。 db)

self.conn.cursor()


def random_quote():

"""

计算MS Access数据库Quotations2005.mdb中的所有引号。

随机选择一个引号并使用textwrap显示它。

""

c =连接(''DSN = Quotations'')

c.execute(" SELECT COUNT(Quote)FROM PythonQuoteQuery")


BartlebyScrivener写道:


我只是一个业余爱好者。花了几个小时试图上课,

,因为我认为这是一个我需要的场合。但是我不能让它工作。


这段代码工作 (仅仅是因为全局c,我知道我应该通过使用类来避免
)。我编辑了其余部分,遗漏了

无关的格式和打印报价。


我已多次阅读过类,但我不知道't得到他们呢。

显然。如果我能解决这样一个现实生活中的问题,那么也许

我会看到光。


如果我正确理解了类的强大功能,我可以制作一个

允许我创建一个新实例,它可以连接到一个

SQLite3数据库而不是Access数据库,以及创建更多方法

将执行不同的SQL搜索。


感谢您的帮助,


rd


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


导入mx.ODBC.Windows为odbc

导入系统

随机导入


def connect():

global c



这意味着你想使用一个尚不存在的全局变量c,

一个例子是将此代码保存到文件中:


#!/ usr / bin / env python


c = 0

def test_global():

global c

c = 1


打印c


当你运行它时会打印0


db =''DSN = Quotations''

conn = odbc.DriverConnect(db)

c = conn.cursor()


def random_quote():

"""

计算MS Access数据库Quotations2005.mdb中的所有引号。

随机选择一个引号并使用textwrap显示它。

"""

c.execute(" SELECT COUNT(Quote)FROM PythonQuoteQuery")

#在报价字段中产生带有行数的行数

total_quotes = c.fetchone()

#获取一个介于1和总数之间的随机数

报价

quote_number =(随机。 randint(1,total_quotes [0]),)

#选择ID与该数字匹配的引用

c.execute(" SELECT Author,Quote FROM PythonQuoteQuery WHERE ID =?",

quote_数量)

quote = c.fetchone()

blah blah blah


def print_quote()

代码格式化和打印报价(除非我学习课程,否则还必须是全局的b $ b。)



一个类结构可能看起来像 - 请记住我不知道
知道mx.ODBC.Windows - 我想它不完全符合DB-API,

,因为你没有使用连接方法。


class SQLQuery(object):

"""连接到的对象数据库并且可以执行SQL

命令

""

def __init __(self,conn):

""" conn是字典{''serverId'':XX,''userId'':YY,

''passWord'':ZZ}

""

self.connection = connect(conn [''userId''],conn [''passWord''],

conn [''serverId''])

self.cursor = self .__ connection.cursor()


def select(self,selectqry):

"""参数selectqry指定sql返回数据,如

选择

""

self.cursor.execute(selectqry)

返回self.cursor.fetchall()

sql = SQLQuery(''serverId'':''XX'',''userId'':''YY'' ,''passWord'':''ZZ'')

qoutes = sql.select(" SELECT COUNT(Quote)FROM PythonQuoteQuery")

打印报价


if __name__ ==''__ main__'':

if len(sys.argv)== 1:


sys.argv是一个列表,其中第一个参数是运行的

脚本的名称,第二个元素是第一个参数,等等。


connect()

random_quote()

print_quote()


BartlebyScrivener写道:


我只是一个爱好者。花了几个小时试图上课,

,因为我认为这是一个我需要的场合。但是我不能让它工作。


这段代码工作 (仅仅是因为全局c,我知道我应该通过使用类来避免
)。我编辑了其余部分,遗漏了

无关的格式和打印报价。


我已多次阅读过类,但我不知道't得到他们呢。

显然。如果我能解决这样一个现实生活中的问题,那么也许

我会看到光。


如果我正确理解了类的强大功能,我可以制作一个

允许我创建一个新实例,它可以连接到一个

SQLite3数据库而不是Access数据库,以及创建更多方法

将执行不同的SQL搜索。


感谢您的帮助,


rd


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


导入mx.ODBC.Windows为odbc

导入系统

随机导入


def connect():

global c

db =''DSN = Quotations''

conn = odbc.DriverConnect(db)

c = conn.cursor()

def random_quote():

"""

计算MS Access数据库Quotations2005.mdb中的所有引号。

随机选择一个引号并使用t显示它extwrap。

""

c.execute(" SELECT COUNT(Quote)FROM PythonQuoteQuery")

#Yields the引号字段中包含某些内容的行数

total_quotes = c.fetchone()

#获取一个介于1和总数之间的随机数

报价

quote_number =(random.randint(1,total_quotes [0]),)

#选择ID与该数字匹配的报价

c.execute(" SELECT Author,Quote FROM PythonQuoteQuery WHERE ID =?",

quote_number)

quote = c.fetchone()

blah blah blah


def print_quote()

格式和打印报价的代码(也必须是

global,除非我学习类!)


if __name__ ==''__ main__'':

if len(sys.argv) == 1:

connect()

random_quote()

print_quo te()



你真的不需要上课,只需参数+返回值。

可能最好是掌握参与的想法+返回值

然后再继续上课。这被称为程序性的。编程。

请注意,由于严格的python

命名空间没有名称冲突(根据Tim Peters的说法,这是个好主意。)

For例如:


def connect():

db =''DSN = Quotations''

conn = odbc.DriverConnect( db)

c = conn.cursor()

#注意返回值:

返回c


def random_quote(c):#< ==注意参数

"""

计算MS Access数据库Quotations2005.mdb中的所有引号。

随机挑选一个引号并使用textwrap显示它。

""

c.execute(" SELECT COUNT (引用)FROM PythonQuoteQuery")

#在引用字段中产生带有内容的行数

total_quotes = c.fetchone()

#在1和...之间取一个随机数...

quote_number =(random.randint(1,total_quotes [0]),)

#选择一个引用的地方ID匹配该数字

q =" SELECT作者,引用FROM PythonQuoteQuery WHERE ID =?"

c.execute(q,quote_number)

quote = c.fetchone()

#注意返回值:

返回报价


def print_quote(quote): #< ==注意参数

打印报价#< ==如果你想做什么


if __name__ ==''__ main__'':

如果len(sys.argv)== 1:

c = connect()#< ==没有碰撞:NAMESPACES

quote = random_quote(c)#< == DITTO

print_quote(引用)#你有它

James


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()

解决方案

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.DriverConnect(self.db)
self.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 = Connection(''DSN=Quotations'')
c.execute ("SELECT COUNT(Quote) FROM PythonQuoteQuery")


BartlebyScrivener 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=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!)

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.__connection.cursor()

def select(self, selectqry):
"""argument selectqry specifies a sql which returns data, like a
select
"""
self.cursor.execute(selectqry)
return self.cursor.fetchall()

sql = SQLQuery(''serverId'': ''XX'', ''userId'': ''YY'', ''passWord'': ''ZZ'')
qoutes = sql.select("SELECT COUNT(Quote) FROM PythonQuoteQuery")
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()


BartlebyScrivener 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=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()

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=Quotations''
conn = odbc.DriverConnect(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 PythonQuoteQuery")
# 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 PythonQuoteQuery WHERE ID=?"
c.execute (q, quote_number)
quote = c.fetchone()
# NOTE THE RETURN VALUE:
return quote

def print_quote(quote): # <== 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(quote) # THERE YOU HAVE IT
James


这篇关于帮助我第一次使用课程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆