python - 如何在 Python 3.5+ 中将 __format__ 添加到 namedtuple?

标签 python string python-3.x string-formatting

我正在使用为早期版本的 Python 编写的代码。

TensorShape = namedtuple('TensorShape', ['batch_size', 'channels', 'height', 'width'])

稍后,我有这个(删节的)代码:

s = [hdr, '-' * 94]
...
s.append('{:<20} {:<30} {:>20} {:>20}'.format(node.kind, node.name, data_shape,
                                                          tuple(out_shape)))

tuple(out_shape) 上爆炸,但有异常(exception)

TypeError: unsupported format string passed to tuple.__format__

因为 out_shape 是一个 TensorShape 并且它没有定义 __format__ 方法。

所以我将 TensorShape 的定义更改为

def format_tensorshape(format_spec):
    return format("{0} {1} {2} {3}")

TensorShape = namedtuple('TensorShape', ['batch_size', 'channels', 'height', 'width'])
TensorShape.__format__ = format_tensorshape

但是这段代码仍然会在下游爆炸并出现同样的异常。

我做错了什么?

最佳答案

您走在正确的轨道上——只需连接 two arguments传递给 format_tensorshape 到您对 format 的调用:

import collections
def format_tensorshape(self, format_spec):
    return format("{0} {1} {2} {3}".format(*self), format_spec)

TensorShape = collections.namedtuple('TensorShape', ['batch_size', 'channels', 'height', 'width'])
TensorShape.__format__ = format_tensorshape

out_shape = TensorShape(1,2,3,4)
print('{:>20}'.format(out_shape))

产量

             1 2 3 4

关于python - 如何在 Python 3.5+ 中将 __format__ 添加到 namedtuple?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45625263/

相关文章:

c++ - CORBA::String_var -> 我无法为这种类型的类字段分配任何值

python - 用类模拟产量

python - Matplotlib:检查空图

python - 将存储在数据库中的 BLOB 转换为 HTML 网站上的图像

javascript - 难倒 : IE8 Message: Expected identifier, 字符串或数字行:82 字符:1 代码:0

当我调整图片大小时,Python 图像库生成质量差的 jpeg

Java Map,如何正确将UTF-8字符串放入 map ?

python-3.x - 导入错误 : The HttpLocust class has been renamed to HttpUser in version 1. 0

python - 我如何根据使用 to_html 从 pd.DataFrame 生成的 HTML 表的值更改颜色

python - python中 'in'对不同数据结构的操作效率