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 ? 11 3368
>
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
On 21 Jan 2007 14:35:19 -0800, Nanjundi <na******@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
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...)
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
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.
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 ?
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" ?
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
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 This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
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'
|
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 arguments, got 0". Tested with Python 2.3.4 on
OpenBSD and Python 2.4 on Win98; same results. Is this a bug in
deepcopy, how I dynamically assign the...
|
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 a method object, bound to instance, or
unbound if
> instance is None. function must be callable.
However, some simple experiments I've tried seem...
|
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 2.1. That is, rather than
if type(x) == types.ListType:
I now do:
|
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 following, it doesn't work and is
wondering if it is a bug or intended :
>>> import operator
>>> import new
| |
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?
|
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 again later.
Sometimes the callable ``foo`` is actually a bound method, e.g.
``bar.baz``, but in such cases, pickle doesn't work by default because...
|
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 = registry
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language...
|
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
| |
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules.
He will explain when you may want to use classes...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
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 we have to send another system
|
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 can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...
| |