【发布时间】:2017-08-11 00:30:13
【问题描述】:
我正在使用为早期版本的 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) 上爆炸了,但例外
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
但是这段代码仍然会在下游发生同样的异常。
我做错了什么?
【问题讨论】:
-
当应用于元组时,您期望
{:>20}的行为是什么?调用tuple(out_shape)是一个空操作(out_shape已经是一个元组),但是如果你想将它显示为(batch_size, channels, height, width),你可以简单地调用str(out_shape)。由于这是一个字符串,格式化指令应该可以按预期工作。 -
@larsks 如果你使用 str(out_shape) 那么你会得到类和方法的名称以及值,而不是(batch_size、channels、height、width)。
-
对,
str(tuple(...)),我猜。
标签: python string python-3.x string-formatting