instancemethod

Gert Cuykens gert.cuykens at gmail.com
Tue Jan 23 16:11:42 EST 2007


import MySQLdb

class Db(object):

    def __enter__(self):
        pass

    def __init__(self,server,user,password,database):
        self._db=MySQLdb.connect(server , user , password , database)
        self._db.autocommit(True)
        self.cursor=self._db.cursor()

    def execute(self,cmd):
        self.cursor.execute(cmd)
        self.rowcount=int(self.cursor.rowcount)

    def close(self):
        self.cursor.close()
        self._db.close()

    def __getattr__(self, name):
        attr = getattr(self._cursor, name,getattr(self._db, name,  None))
        if attr is None:
            raise AttributeError("object %s has no attribute %s"
%(self.__class__.__name__, name))
        return attr

    def __del__(self):
        try:
            self.close()
        finally:
            pass
        except:
            pass

    def __exit__(self):
        pass

if __name__ == '__main__':
    gert = Db('localhost','root','*****','gert')
    gert.execute('select * from person')
    for row in gert.cursor:
        print row

    with Db('localhost','root','*****','gert') as gert:
        gert.excecute('select * from person')
        for row in gert.cursor:
            print row

Desktop/svn/db/Py/db.py:45: Warning: 'with' will become a reserved
keyword in Python 2.6
  File "Desktop/svn/db/Py/db.py", line 45
    with Db('localhost','root','*****','gert') as gert:
          ^
SyntaxError: invalid syntax

I was thinking if it would be possible to create a object that uses
it's own instance name as a atribute.

For example instead of
gert = Db('localhost','root','*****','gert')

you would do this
gert = Db('localhost','root','*****')

and the name of the object itself 'gert' get's assigned to database somehow ?



More information about the Python-list mailing list