Exercise 5.2 - Solution

(b) Using Inheritance

# tableformat.py

class TableFormatter(object):
    def headings(self, headers):
        '''
        Emit the table headings
        '''
        raise NotImplementedError()

    def row(self, rowdata):
        '''
        Emit a single row of table data
        '''
        raise NotImplementedError()

class TextTableFormatter(TableFormatter):
    '''
    Emit a table in plain-text format
    '''
    def headings(self, headers):
        for h in headers:
            print '%10s' % h,
        print
        print ('-'*10 + ' ')*len(headers)

    def row(self, rowdata):
        for d in rowdata:
            print '%10s' % d,
        print

class CSVTableFormatter(TableFormatter):
    '''
    Output portfolio data in CSV format.
    '''
    def headings(self, headers):
        print ','.join(headers)

    def row(self, rowdata):
        print ','.join(rowdata)

class HTMLTableFormatter(TableFormatter):
    '''
    Output portfolio data in HTML format.
    '''
    def headings(self, headers):
        print '<tr>',
        for h in headers:
            print '<th>%s</th>' % h,
        print '</tr>'

    def row(self, rowdata):
        print '<tr>',
        for d in rowdata:
            print '<td>%s</td>' % d,
        print '</tr>'

(c) Polymorphism in Action

# tableformat.py
...

def create_formatter(name):
    '''
    Create an appropriate formatter given an output format name
    '''
    if name == 'txt':
        return TextTableFormatter()
    elif name == 'csv':
        return CSVTableFormatter()
    elif name == 'html':
        return HTMLTableFormatter()
    else:
        raise RuntimeError('Unknown table format %s' % name)

[ Back ]