instancemethod

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Mon Jan 22 15:06:29 EST 2007


Gert Cuykens a écrit :
> import MySQLdb
> 
> class Db:
(snip)
>    def excecute(self,cmd):
>        self._cursor.execute(cmd)
>        self._db.commit()
> 
What about autocommit and automagic delegation ?

import MySQLdb

class Db(object):
    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 close(self):
        self._cursor.close()
        self._db.close()

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

    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

(NB :not tested...)



More information about the Python-list mailing list