python-3.x - 在以下行中: 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)
解决方案
推荐阅读
- css - gtkmm 3.10.1 中带有 CSS 的 Gtk::Box 样式问题
- reactjs - 在部署在 kubernetes 上的 React JS 项目中使用配置映射
- mysql - 频繁更新单个表与使用另一个表和 CRON 将更改导入 MySQL 中的主表?
- java - 从注解处理器生成 Spring 组件
- ios - 为什么多次购买消耗品?
- sql - Oracle - 将计算的数字字段与字符串字段连接起来
- asp.net-core - 是否可以访问另一个 blazor 电路?
- python - 从多种数据类型二维数组python中删除单引号
- java - 无法使用 Windows Biometric Framework 捕获图像数据
- java - Java AOP在构造对象时设置字段值