473,503 Members | 2,698 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

instancemethod

import MySQLdb

class Db:

_db=-1
_cursor=-1

@classmethod
def __init__(self,server,user,password,database):
self._db=MySQLdb.connect(server , user , password , database)
self._cursor=self._db.cursor()

@classmethod
def excecute(self,cmd):
self._cursor.execute(cmd)
self._db.commit()

@classmethod
def rowcount(self):
return int(self._cursor.rowcount)

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

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

if __name__ == '__main__':
gert=Db('localhost','root','******','gert')
gert.excecute('select * from person')
for x in range(0,gert.rowcount):
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.rowcount):
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 ?
Jan 21 '07 #1
11 3363
>
if __name__ == '__main__':
gert=Db('localhost','root','******','gert')
gert.excecute('select * from person')
for x in range(0,gert.rowcount):
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.rowcount):
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.rowcount):
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

Jan 21 '07 #2
On 21 Jan 2007 14:35:19 -0800, Nanjundi <na******@gmail.comwrote:

if __name__ == '__main__':
gert=Db('localhost','root','******','gert')
gert.excecute('select * from person')
for x in range(0,gert.rowcount):
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.rowcount):
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.rowcount):
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
Jan 21 '07 #3
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...)
Jan 22 '07 #4
Reading all of the above this is the most simple i can come too.

import MySQLdb

class Db:

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 excecute(self,cmd):
self.cursor.execute(cmd)
self.rowcount=int(self.cursor.rowcount)

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

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

if __name__ == '__main__':
gert=Db('localhost','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
Jan 22 '07 #5
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,server,user,password,database):
self._db=MySQLdb.connect(server , user , password , database)
self._db.autocommit(True)
self.cursor=self._db.cursor()

def excecute(self,cmd):
Just out of curiousity: is there any reason you spell it "excecute"
instead of "execute" ?
self.cursor.execute(cmd)
self.rowcount=int(self.cursor.rowcount)

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

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

if __name__ == '__main__':
gert=Db('localhost','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.
Jan 23 '07 #6
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 ?
Jan 23 '07 #7
Gert Cuykens a écrit :
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)
isn't cursor.rowcount already an int ?
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
The finally clause is useless here.
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.
class Obj(object):
pass

toto = tutu = tata = titi = Obj()

What's an "instance name" ?

Jan 26 '07 #8
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__.__name__[3] == toto

And if your obj is a argument like

something(Obj())

i would say __object__.__name__[0] == 0x2b7bd17e9910
Jan 26 '07 #9
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."

http://www.die.net/doc/linux/man/man2/close.2.html

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

Jan 27 '07 #10
"Steven D'Aprano" <st***@REMOVE.THIS.cybersource.com.auescribió en el
mensaje
news:pa****************************@REMOVE.THIS.cy bersource.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
Jan 27 '07 #11
On Sat, 27 Jan 2007 01:03:50 -0300, Gabriel Genellina wrote:
"Steven D'Aprano" <st***@REMOVE.THIS.cybersource.com.auescribió en el
mensaje
news:pa****************************@REMOVE.THIS.cy bersource.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.

Jan 27 '07 #12

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
1792
by: Rim | last post by:
Hi, It appears to me the simplest way to add a function to a class outside of the class declaration is as follows: >>> class a(object): .... pass .... >>> def f(self): .... print 'hi'
7
3946
by: ‘5ÛHH575-UAZWKVVP-7H2H48V3 | last post by:
(see end of message for example code) When an instance has a dynamically assigned instance method, deepcopy throws a TypeError with the message "TypeError: instancemethod expected at least 2...
1
1844
by: Martin Miller | last post by:
In section "3.27 new -- Creation of runtime internal objects" of the documentation that comes with Python 2.4 it says: > instancemethod(function, instance, class) > > This function will return...
7
2113
by: John Reese | last post by:
Why hello there ha ha. I have got in the habit of testing the types of variables with isinstance and the builtin type names instead of using the types module, as was the style back around Python...
4
1510
by: bonono | last post by:
I came across this while searching for a way to DIY partial(), until it is available in 2.5 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/229472 However, when trying for the...
6
12306
by: Jim Lewis | last post by:
Pickling an instance of a class, gives "can't pickle instancemethod objects". What does this mean? How do I find the class method creating the problem?
2
2130
by: Steven Bethard | last post by:
I'd like to be able to pickle instancemethod objects mainly because I want to be able to delay a call like ``foo(spam, badger)`` by dumping ``foo``, ``spam`` and ``badger`` to disk and loading them...
2
3504
by: Michele Simionato | last post by:
Can somebody explain what's happening with the following script? $ echo example.py import pickle class Example(object): def __init__(self, obj, registry): self._obj = obj self._registry =...
0
7261
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
7315
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
6974
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
7445
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
5559
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
1
4991
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
1492
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
1
721
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
369
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.