instancemethod

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Gert Cuykens

    #1

    instancemethod

    import MySQLdb

    class Db:

    _db=-1
    _cursor=-1

    @classmethod
    def __init__(self,s erver,user,pass word,database):
    self._db=MySQLd b.connect(serve r , user , password , database)
    self._cursor=se lf._db.cursor()

    @classmethod
    def excecute(self,c md):
    self._cursor.ex ecute(cmd)
    self._db.commit ()

    @classmethod
    def rowcount(self):
    return int(self._curso r.rowcount)

    @classmethod
    def fetchone(self):
    return self._cursor.fe tchone()

    @classmethod
    def close(self):
    self._cursor.cl ose()
    self._db.close( )

    if __name__ == '__main__':
    gert=Db('localh ost','root','** ****','gert')
    gert.excecute(' select * from person')
    for x in range(0,gert.ro wcount):
    print gert.fetchone()
    gert.close()

    gert@gert:~$ python ./Desktop/svn/db/Py/db.py
    Traceback (most recent call last):
    File "./Desktop/svn/db/Py/db.py", line 35, in <module>
    for x in range(0,gert.ro wcount):
    TypeError: range() integer end argument expected, got instancemethod.
    gert@gert:~$

    Can anybody explain what i must do in order to get integer instead of
    a instance ?
  • Nanjundi

    #2
    Re: instancemethod

    >
    if __name__ == '__main__':
    gert=Db('localh ost','root','** ****','gert')
    gert.excecute(' select * from person')
    for x in range(0,gert.ro wcount):
    print gert.fetchone()
    gert.close()
    >
    gert@gert:~$ python ./Desktop/svn/db/Py/db.py
    Traceback (most recent call last):
    File "./Desktop/svn/db/Py/db.py", line 35, in <module>
    for x in range(0,gert.ro wcount):
    TypeError: range() integer end argument expected, got instancemethod.
    gert@gert:~$
    >
    Can anybody explain what i must do in order to get integer instead of
    a instance ?
    Gert,
    for x in range(0,gert.ro wcount):
    gert.rowcount is the method (and not a data attribute).
    gert.rowcount() is the method call, which get the return value from
    method.

    So try this.
    for x in range( 0,gert.rowcount () ):

    -N

    Comment

    • Gert Cuykens

      #3
      Re: instancemethod

      On 21 Jan 2007 14:35:19 -0800, Nanjundi <nanjundi@gmail .comwrote:

      if __name__ == '__main__':
      gert=Db('localh ost','root','** ****','gert')
      gert.excecute(' select * from person')
      for x in range(0,gert.ro wcount):
      print gert.fetchone()
      gert.close()

      gert@gert:~$ python ./Desktop/svn/db/Py/db.py
      Traceback (most recent call last):
      File "./Desktop/svn/db/Py/db.py", line 35, in <module>
      for x in range(0,gert.ro wcount):
      TypeError: range() integer end argument expected, got instancemethod.
      gert@gert:~$

      Can anybody explain what i must do in order to get integer instead of
      a instance ?
      >
      Gert,
      for x in range(0,gert.ro wcount):
      gert.rowcount is the method (and not a data attribute).
      gert.rowcount() is the method call, which get the return value from
      method.
      >
      So try this.
      for x in range( 0,gert.rowcount () ):
      >
      Doh! :)

      thx

      Comment

      • Bruno Desthuilliers

        #4
        Re: instancemethod

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

        import MySQLdb

        class Db(object):
        def __init__(self,s erver, user, password, database):
        self._db = MySQLdb.connect (server , user , password , database)
        self._db.autoco mmit(True)
        self._cursor = self._db.cursor ()

        def close(self):
        self._cursor.cl ose()
        self._db.close( )

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

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

        (NB :not tested...)

        Comment

        • Gert Cuykens

          #5
          Re: instancemethod

          Reading all of the above this is the most simple i can come too.

          import MySQLdb

          class Db:

          def __init__(self,s erver,user,pass word,database):
          self._db=MySQLd b.connect(serve r , user , password , database)
          self._db.autoco mmit(True)
          self.cursor=sel f._db.cursor()

          def excecute(self,c md):
          self.cursor.exe cute(cmd)
          self.rowcount=i nt(self.cursor. rowcount)

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

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

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

          This must be the most simple it can get right ?

          PS i didn't understand the __getattr__ quit well but i thought it was
          just to overload the privies class

          Comment

          • Bruno Desthuilliers

            #6
            Re: instancemethod

            Gert Cuykens a écrit :
            Reading all of the above this is the most simple i can come too.
            >
            import MySQLdb
            >
            class Db:
            >
            def __init__(self,s erver,user,pass word,database):
            self._db=MySQLd b.connect(serve r , user , password , database)
            self._db.autoco mmit(True)
            self.cursor=sel f._db.cursor()
            >
            def excecute(self,c md):
            Just out of curiousity: is there any reason you spell it "excecute"
            instead of "execute" ?
            self.cursor.exe cute(cmd)
            self.rowcount=i nt(self.cursor. rowcount)
            >
            def close(self):
            self.cursor.clo se()
            self._db.close( )
            >
            def __del__(self):
            try:
            self.close()
            except:
            pass

            if __name__ == '__main__':
            gert=Db('localh ost','root','** ****','gert')
            gert.excecute(' select * from person')
            for row in gert.cursor:
            print row
            >
            This must be the most simple it can get right ?
            Using __getattr__ is still simpler.
            PS i didn't understand the __getattr__ quit well but i thought it was
            just to overload the privies class
            The __getattr__ method is called when an attribute lookup fails (and
            remember that in Python, methods are -callable- attributes). It's
            commonly used for delegation.

            Comment

            • Gert Cuykens

              #7
              Re: instancemethod

              import MySQLdb

              class Db(object):

              def __enter__(self) :
              pass

              def __init__(self,s erver,user,pass word,database):
              self._db=MySQLd b.connect(serve r , user , password , database)
              self._db.autoco mmit(True)
              self.cursor=sel f._db.cursor()

              def execute(self,cm d):
              self.cursor.exe cute(cmd)
              self.rowcount=i nt(self.cursor. rowcount)

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

              def __getattr__(sel f, name):
              attr = getattr(self._c ursor, name,getattr(se lf._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('s elect * 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 ?

              Comment

              • Bruno Desthuilliers

                #8
                Re: instancemethod

                Gert Cuykens a écrit :
                import MySQLdb
                >
                class Db(object):
                >
                def __enter__(self) :
                pass
                >
                def __init__(self,s erver,user,pass word,database):
                self._db=MySQLd b.connect(serve r , user , password , database)
                self._db.autoco mmit(True)
                self.cursor=sel f._db.cursor()
                >
                def execute(self,cm d):
                self.cursor.exe cute(cmd)
                self.rowcount=i nt(self.cursor. rowcount)
                isn't cursor.rowcount already an int ?
                def close(self):
                self.cursor.clo se()
                self._db.close( )
                >
                def __getattr__(sel f, name):
                attr = getattr(self._c ursor, name,getattr(se lf._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
                The finally clause is useless here.
                def __exit__(self):
                pass
                >
                if __name__ == '__main__':
                gert = Db('localhost', 'root','*****', 'gert')
                gert.execute('s elect * 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.
                class Obj(object):
                pass

                toto = tutu = tata = titi = Obj()

                What's an "instance name" ?

                Comment

                • Gert Cuykens

                  #9
                  Re: instancemethod

                  class Obj(object):
                  pass
                  >
                  toto = tutu = tata = titi = Obj()
                  >
                  What's an "instance name" ?
                  >
                  --
                  http://mail.python.org/mailman/listinfo/python-list
                  i would say __object__.__na me__[3] == toto

                  And if your obj is a argument like

                  something(Obj() )

                  i would say __object__.__na me__[0] == 0x2b7bd17e9910

                  Comment

                  • Steven D'Aprano

                    #10
                    Re: instancemethod

                    On Fri, 26 Jan 2007 17:25:37 +0100, Bruno Desthuilliers wrote:
                    > def __del__(self):
                    > try:
                    > self.close()
                    > finally:
                    > pass
                    > except:
                    > pass
                    >
                    The finally clause is useless here.

                    In principle, closing a file could raise an exception. I've never seen it
                    happen, but it could. From the Linux man pages:

                    "Not checking the return value of close() is a common but nevertheless
                    serious programming error. It is quite possible that errors on a previous
                    write(2) operation are first reported at the final close(). Not checking
                    the return value when closing the file may lead to silent loss of data.
                    This can especially be observed with NFS and with disk quota."

                    close() closes a file descriptor, so that it no longer refers to any file and may be reused. Any record locks (see fcntl(2)) held on the file it was ...


                    I assume that the same will apply in Python.

                    It has to be said, however, that the error recovery shown ("pass") is
                    fairly pointless :-)


                    --
                    Steven

                    Comment

                    • Gabriel Genellina

                      #11
                      Re: instancemethod

                      "Steven D'Aprano" <steve@REMOVE.T HIS.cybersource .com.auescribió en el
                      mensaje
                      news:pan.2007.0 1.27.00.07.59.3 87012@REMOVE.TH IS.cybersource. com.au...
                      On Fri, 26 Jan 2007 17:25:37 +0100, Bruno Desthuilliers wrote:
                      >> def __del__(self):
                      >> try:
                      >> self.close()
                      >> finally:
                      >> pass
                      >> except:
                      >> pass
                      >>
                      >The finally clause is useless here.
                      >
                      In principle, closing a file could raise an exception. I've never seen it
                      happen, but it could. From the Linux man pages: [...]
                      I assume that the same will apply in Python.
                      Note that he said that the *finally* clause were useless (and I'd say so,
                      too), not the *except* clause.
                      And yes, in Python it is checked - when the close method was called
                      explicitely, an exception is raised; when called when the object is garbage
                      collected, a message is printed on sys.stderr
                      It has to be said, however, that the error recovery shown ("pass") is
                      fairly pointless :-)
                      Only supresses the message on sys.stderr - exceptions raised on __del__ are
                      never propagated.

                      --
                      Gabriel Genellina


                      Comment

                      • Steven D'Aprano

                        #12
                        Re: instancemethod

                        On Sat, 27 Jan 2007 01:03:50 -0300, Gabriel Genellina wrote:
                        "Steven D'Aprano" <steve@REMOVE.T HIS.cybersource .com.auescribió en el
                        mensaje
                        news:pan.2007.0 1.27.00.07.59.3 87012@REMOVE.TH IS.cybersource. com.au...
                        >
                        >On Fri, 26 Jan 2007 17:25:37 +0100, Bruno Desthuilliers wrote:
                        >>> def __del__(self):
                        >>> try:
                        >>> self.close()
                        >>> finally:
                        >>> pass
                        >>> except:
                        >>> pass
                        >>>
                        >>The finally clause is useless here.
                        >>
                        >In principle, closing a file could raise an exception. I've never seen it
                        >happen, but it could. From the Linux man pages: [...]
                        >I assume that the same will apply in Python.
                        >
                        Note that he said that the *finally* clause were useless (and I'd say so,
                        too), not the *except* clause.
                        Doh!

                        Yes, he's right. Worse, the code as show can't possibly work: the finally
                        clause must come AFTER the except clause.
                        >>try:
                        .... pass
                        .... finally:
                        .... pass
                        .... except:
                        File "<stdin>", line 5
                        except:
                        ^
                        SyntaxError: invalid syntax



                        --
                        Steven.

                        Comment

                        Working...