[Tutor] yet another question on OO inheritance

Serdar Tumgoren zstumgoren at gmail.com
Tue Aug 18 19:47:06 CEST 2009


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:

Committee(object):...

CandidateCommittee(Committee):
    def get_data(self):
        sql = """
        select id, name
        from table_candidates
        """
       # execute sql and do stuff with the data


PresidentialCommittee(Committee):
    def get_data(self):
        sql = """
        select id, name
        from table_prez
        """
        # execute sql and do stuff with 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?

Would I need to do type-checking with "isinstance"? And if so, how
does one implement that in this case?  I figured overriding the
get_data method would simply clobber the sql I'm trying to inherit,
which of course defeats the purpose.

Can anyone suggest an approach?

Regards,
Serdar


More information about the Tutor mailing list