problem with writing a simple module

Larry Bates larry.bates at websafe.com
Mon May 22 10:04:09 EDT 2006


nephish at xit.net wrote:
> ello there. i am having a problem getting a module to work right.
> 
> i wrote a class that is going to be used in a few different scripts in
> the same directory.
> 
> it looks like this:
> 
> #!/usr/bin/python
> 
> import MySQLdb
> 
> class DbConnector(object):
> 	"""
> 	Database Connection object.
> 	class receives the db argument to specify the database.
> 	"""
> 
> 	def __init__(self, db='test_db', host="10.10.10.16",user="me",
> passwd="mypass"):
> 		self.host   =   host
> 		self.user   =   user
> 		self.passwd =   passwd
> 		self.db = db
> 		# Unpack Other Database Arguments Here
> 		self.CreateConnection()
> 
> 	def createConnection(self):
> 		self.connection = MySQLdb.connect(self.host, self.user, self.passwd,
> self.db)
> 
> 	def killConnection(self):
> 		self.connection.close()
> 
> 	def getMany(self, sql_statement):
> 		cursor = self.connection.cursor()
> 		try:
> 			cursor.execute(sql_statement)
> 			result = cursor.fetchall()
> 			self.connection.close()
> 			return result
> 		except:
> 			self.connection.close()
> 
> the file is saved as DbConnector.py and made executable.
> then i get this in idle
> 
>>> import DbConnector
>>> x = DbConnector()
> 
> then it tells me that the module object is not callable.
> 
> this works though
>>> import DbConnector
>>> x = DbConnector
>>> x.db = 'other_db'
>>> results = x.getOne("SELECT * FROM `stuff`")
> 
> it tells me that the module has no attribute getOne.
> 
> i am really not trying for an attribute, but a method.
> 
> anyone know what i am doing wrong?
> 
> thanks
> 
You can do either:

from DbConnector import *
x=DbConnector()

or (preferred method these days)

import DbConnector
x=DbConnector.DbConnector()

When you zay x=DbConnector all you are doing is setting a
variable (pointer) x that points to the class DBconnector,
which is basically an alias.  x in fact would not have
a getOne method as it hasn't been instantiated yet.

-Larry Bates



More information about the Python-list mailing list