我有一个类Commit
。在
class Commit:
def __init__(self, uid, message):
self.uid = uid
self.message = message
def __str__(self):
print(self.__dict__)
return textwrap.dedent('''\
Commit: {uid}
{message}
''').format(self.__dict__)
这在我看来是正确的;这两个键都存在并且都是非None
,如print
调用的输出所示:
但是,对列表行中的str.format()
的调用会引发一个KeyError
。在
Traceback (most recent call last): File "../Pynewood/pnw", line 7, in cli(sys.argv) File "/Users/daknok/Desktop/Pynewood/pynewood/cli.py", line 11, in cli print(commit) File "/Users/daknok/Desktop/Pynewood/pynewood/commit.py", line 14, in __str__ ''').format(self.__dict__) KeyError: 'uid'
为什么我得到这个错误,而这些键显然存在于字典中?在
Radek Slupik是对的,
str.format
需要单独的关键字参数,在问题的代码中,dict
只是作为第一个位置参数传递给format
,该参数将在格式字符串中的{0}
上扩展。所以应该使用str.format(**mapping)
。在但从python3.2开始,您可以使用
str.format_map(mapping)
。它的工作原理与str.format(**mapping)
相似,但它不会将映射转换为dict
。这使我们可以为format
提供自定义映射类,如文档中的示例所示:它看起来也更好,可能会稍微提高性能。在
^{} 需要kwargs,因此需要使用
**
扩展字典。在相关问题 更多 >
编程相关推荐