operator creation?

G

Gerardo Herzig

Hi all. Ill try to explain mi situation:
Lets say i have an DB object, who implements the querys to the database
trough a method called DBObject.doQuery.

On the other hand, i have 50 sql functions stored in the database. So i
can call DBObject.doQuery('select * from my_sql_function()')...Ok, what
do i want to achieve, is some mecanism to be able to call

DBObject.my_sql_function(), but without actually having to declare the
method called "my_sql_function". May be with creating a `->' operator...
maybe overrwriting the '.' operator...


Im not shure. If someone understand my problem (and my poor english),
please help :)

Gerardo
 
P

Peter Otten

Gerardo said:
Lets say i have an DB object, who implements the querys to the database
trough a method called DBObject.doQuery.

On the other hand, i have 50 sql functions stored in the database. So i
can call DBObject.doQuery('select * from my_sql_function()')...Ok, what
do i want to achieve, is some mecanism to be able to call

DBObject.my_sql_function(), but without actually having to declare the
method called "my_sql_function". May be with creating a `->' operator...
maybe overrwriting the '.' operator...

That's what __getattr__() is for. It is called when an attribute of the
DBObject instance doesn't exist. The function 'method' defined inside
__getattr__() remembers what the variable sql is bound to on that
particular call ("closure"). Because we update the class with 'method',
instead of __getattr__() subsequent calls will not my_sql_function()
directly.

class DBObject(object):
def doQuery(self, sql):
print "executing", sql
def __getattr__(self, name):
sql = "SELECT * FROM %s();" % name
def method(self):
return self.doQuery(sql)
# insert the new method into the class
# so that it has to be created only once
setattr(self.__class__, name, method)

return getattr(self, name) # infinite recursion
# prevented by prior setattr()

dbo = DBObject()
dbo.my_sql_function()
dbo.my_other_sql_function()

Peter
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top