我有一个数据结构类和一个表格格式化类,我想在其中格式化一个文件并输出它。如果输出需要更改,我想要在飞行中创建格式化程序的灵活性。
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
有人能帮上忙吗?谢谢
发布于 2018-07-03 04:36:00
**item
无效,因为**
运算符要求命名的变量是字典(映射),而您尚未提供该值(item是字符串)。因此,您需要将item
转换为字典,并在format语句中使用正确的键/值对。
https://stackoverflow.com/questions/51143317
复制相似问题