[Tutor] yet another question on OO inheritance
Kent Johnson
kent37 at tds.net
Tue Aug 18 20:23:05 CEST 2009
On Tue, Aug 18, 2009 at 1:47 PM, Serdar Tumgoren<zstumgoren at gmail.com> wrote:
> Hi all,
>
> I've hit another gray area for an application I'm working on.
> Specifically, I have a campaign Committee object, and then subclasses
> called CandidateCommittee and PresidentialCommittee. Depending on the
> type of committee, I have to execute a series of SQL statements to
> pull data (used to populate instance attributes of each committee
> type).
>
> Several of these queries are identical, except for the table names
> from which I'm pulling the data:
> So I'm thinking I could reduce code duplication by moving the SQL
> queries to the Committee object:
>
> Committee(object):...
>
> def get_data(self):
> sql = """
> select id, name
> from table_'%(tablename)s'
> """ % {'tablename':name}
>
> CandidateCommittee(Committee):...
> def __init__(self):
> super(CandidateCommittee, self).__init()
>
> PresidentialCommittee(Committee):
> def __init__(self):
> super(PresidentialCommittee, self).__init()
>
> But if I do this, how would I set the "name" variable inside the
> "get_data" method when I instantiate one of the subclasses?
A nice way to do this is with a class attribute. For example:
class Committee(object):
def get_data(self):
sql = """
select id, name
from table_'%(tablename)s'
""" % {'tablename':self.tablename}
class CandidateCommittee(Committee):
tablename = 'CandidateTable'
PresidentialCommittee(Committee):
tablename = 'PresidentialTable'
When you call Committee.get_data() it will get tablename from the
class of the instance being used.
Kent
More information about the Tutor
mailing list