【发布时间】:2018-12-11 02:28:45
【问题描述】:
我有一个数据结构类和一个表格格式化类,我想在其中格式化一个文件并输出它。如果需要更改输出,我希望能够灵活地动态创建格式化程序。
class Row(object):
__slots__ = ('date', 'item', 'expiration', 'price')
def __init__(self, date, item, expiration, price=None):
self.date = date
self.item = item
self.expiration = expiration
self.price = ""
if price:
self.price = price
class Formatter(object):
def row(self, rowdata):
for item in rowdata:
print('<obj date="{date}" item="{item}" exp="{expiration}" price="{price}" />\n').format(**item)
def print_table(objects, colnames, formatter):
for obj in objects:
rowdata = [str(getattr(obj, colname)) for colname in colnames]
formatter.row(rowdata)
我是这样称呼的:
data = [Row("20180101", "Apples", "20180201", 1.50),
Row("20180101", "Pears", "20180201", 1.25)]
formatter = Formatter()
print_table(data, ['date','item','expiration','price'], formatter)
我期待看到的是:
<obj date="20180101" item="Apples" exp="20180201" price="1.50" />
<obj date="20180101" item="Pears" exp="20180201" price="1.25" />
我目前收到以下错误:
TypeError: format() argument after ** must be a mapping, not str
有人可以帮忙吗?谢谢
【问题讨论】:
-
您似乎没有在此代码中的任何位置创建字典,但您尝试使用
rowdata,就好像它的元素是字典一样。
标签: python string python-2.7 class data-structures