Gerardo Herzig wrote: > 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 -- http://mail.python.org/mailman/listinfo/python-list