[Tutor] get name of calling class at runtime
Kent Johnson
kent37 at tds.net
Fri Aug 21 20:40:25 CEST 2009
On Fri, Aug 21, 2009 at 1:53 PM, Serdar Tumgoren<zstumgoren at gmail.com> wrote:
> Hi everyone,
> I'm trying to create a data-retriever class that executes certain SQL
> statements based on the name of a calling class (I'm doing this so I
> can group a bunch of SQL statements in one place; they're currently
> scattered all over the program and it's getting unwieldy).
>
> Currently, I'm forced to pass in the name of the "caller" from the
> calling class:
>
> class DataSources(object):
> def getdata(self, caller):
> if caller == 'CallerA':
> # execute sql for callerA
> elif caller == 'CallerB':
> #execute sql for callerB
>
> class CallerA(object):
> def getdata(self):
> caller = self.__class__.__name__
> dao = DataSources()
> dao.getdata(caller)
>
> class CallerB(object):
> def getdata(self):
> caller = self.__class__.__name__
> dao = DataSources()
> dao.getdata(caller)
>
> So I'm wondering, is there any way to have the DataSources class
> access the name of the calling class at runtime, and avoid having to
> pass in the "caller" variable? Perhaps there's some other standard
> approach to this kind of problem?
You could simplify the code above by passing self to DataSources(). Or
make CallerX inherit from DataSources and use the class attribute
trick we talked about before. Or perhaps you should look into
SQLObject or SQLAlchemy?
Kent
More information about the Tutor
mailing list