[Tutor] Time to Use a Global Variable?
Kent Johnson
kent37 at tds.net
Thu Feb 9 03:51:03 CET 2006
Rich Shepard wrote:
> On Wed, 8 Feb 2006, Kent Johnson wrote:
>
>> Evidently closeDb is an instance method of some class you don't show
>> here.
>> Does DBinterface create and maintain a single instance of this class? or
>> some other code creates an instance?
>
>
> Kent,
>
> closeDB() is defined in the class DBinterface. That's the only
> instance for
> the database connection.
>
>> You need to call closeDb on the DBinterface instance, it is not a
>> module-level function. You haven't shown enough code for me to know how
>> the OnFileQuit method might gain access to the DBinterface instance; how
>> do you access other methods for working with the database?
>
>
> I tried calling DBinterface.closeDB(), but python tells me that
> DBinterface
> is not defined. And here I thought that I understood scoping and the use of
> classes.
>
> What shall I provide to help clarify the situation? The class DBinterface
> is about 300 lines long.
OK. Suppose I have
class DB(object):
def __init__(self):
self.conn = getDatabaseConnection()
def closeDb(self):
self.conn.close()
def doSomethingInteresting(self):
self.conn.execute(...)
To use this class, I have to instantiate it:
myDb = DB()
Now I can say
myDb.doSomethingInteresting()
To close the connection, I have to call closeDb() on the *instance* -
myDb - not on the class itself - DB:
myDb.closeDb()
Does this help? If not...where is your code that calls DBinterface to
create an instance of DBinterface? Where do you store the value (the
DBinterface instance)? How do you access it to do something interesting?
Kent
>
> The method closeDB() is defined in the class DBinterface. What I'm trying
> to do is to ensure that the database cursor and connection are closed when
> the user exits from the application. Class DBinterface has a __del__ method
> to clean up if the user forgets to close the open database, so I'm
> trying to
> learn how to explicitly close it.
>
> Thanks,
>
> Rich
>
More information about the Tutor
mailing list