为什么我得到一个KeyError,而密钥显然存在?

2024-10-01 13:44:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个类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调用的输出所示:

^{pr2}$

但是,对列表行中的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'

为什么我得到这个错误,而这些键显然存在于字典中?在


Tags: inselfformatmessageuidclidefline
2条回答

Radek Slupik是对的,str.format需要单独的关键字参数,在问题的代码中,dict只是作为第一个位置参数传递给format,该参数将在格式字符串中的{0}上扩展。所以应该使用str.format(**mapping)。在

但从python3.2开始,您可以使用str.format_map(mapping)。它的工作原理与str.format(**mapping)相似,但它不会将映射转换为dict。这使我们可以为format提供自定义映射类,如文档中的示例所示:

>>> class Default(dict):
...     def __missing__(self, key):
...         return key
...
>>> '{name} was born in {country}'.format_map(Default(name='Guido'))
'Guido was born in country'

它看起来也更好,可能会稍微提高性能。在

^{}需要kwargs,因此需要使用**扩展字典。在

def __str__(self):
    return textwrap.dedent('''\
    Commit: {uid}

    {message}
    ''').format(**self.__dict__)

相关问题 更多 >