首页 > 解决方案 > 在以下行中: formatter.headings(columns) 我不明白为什么使用标题而其他标题放在类中而不使用

问题描述

表格格式.py

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

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

class TextTableFormatter(TableFormatter): ''' 以纯文本格式输出数据。''' def headings(self, headers): for h in headers: print(f'{h:>10s}', end=' ') print() print(('-'*10 + ' ')*len (标题))

def row(self, rowdata):
    for d in rowdata:
        print(f'{d:>10s}', end=' ')
    print()

class CSVTableFormatter(TableFormatter): ''' 以 CSV 格式输出数据。''' def headings(self, headers): print(','.join(headers))

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

class HTMLTableFormatter(TableFormatter): ''' 以 HTML 格式输出数据。''' def headings(self, headers): print('', end='') for h in headers: print(f'{h}', end='') print('')

def row(self, rowdata):
    print('<tr>', end='')
    for d in rowdata:
        print(f'<td>{d}</td>', end='')
    print('</tr>')

类格式错误(异常):通过

def create_formatter(name): ''' 给定输出格式名称 ''' 创建适当的格式化程序 if name == 'txt': return TextTableFormatter() elif name == 'csv': return CSVTableFormatter() elif name == ' html': return HTMLTableFormatter() else: raise FormatError(f'Unknown table format {name}')

def print_table(objects, columns, formatter): ''' 从对象和属性名称列表中创建一个格式良好的表格。''' formatter.headings(columns) for obj in objects: rowdata = [ str(getattr(obj, name)) for name in columns ] formatter.row(rowdata)

标签: python-3.xclassformat

解决方案


推荐阅读