我正在使用为早期版本的 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/