【问题标题】:How do I use getattr in conjunction with dict string formatting?如何将 getattr 与 dict 字符串格式结合使用?
【发布时间】: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


【解决方案1】:

固定代码:

class Formatter(object):
    def row(self, rowdata):
        print('<obj date="{date}" item="{item}" exp="{expiration}" price="{price}" />\n'.format(**rowdata))


def print_table(objects, colnames, formatter):
    for obj in objects:
        rowdata = {colname: str(getattr(obj, colname)) for colname in colnames}
        formatter.row(rowdata)

你有 3 个问题:

  1. 您将 rowdata 视为项目列表,而 rowdata 应该是单个 列名与数据的映射
  2. 您没有创建映射,只创建了结果。 {colname: str(getattr(obj, colname)) for colname in colnames} 在名称和属性之间创建映射。然后,您可以将其传递给 .format(),它会完全正常工作。
  3. 您在print() 函数上使用了format()。你应该在里面的字符串上使用它。

【讨论】:

    【解决方案2】:

    **item 无效,因为** 运算符期望命名变量是字典(映射),而您没有提供(项目是字符串)。因此,您需要将 item 转换为具有格式语句中所需的正确键/值对的字典。

    【讨论】:

      猜你喜欢
      • 2016-11-07
      • 2021-04-08
      • 1970-01-01
      • 1970-01-01
      • 2012-02-12
      • 2019-01-08
      • 1970-01-01
      • 2011-01-04
      • 1970-01-01
      相关资源
      最近更新 更多