当密钥明确存在时,为什么会出现KeyError?

3 python dictionary python-3.x

我上课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__)
Run Code Online (Sandbox Code Playgroud)

在我看来这是对的;Noneprint调用的输出可以看出,这两个键都存在,并且都不是:

{'message': 'Hello, world!', 'uid': 1}
Run Code Online (Sandbox Code Playgroud)

但是,str.format()对列表行的调用会引发一个KeyError

追溯(最近一次通话):
  在第7行中输入文件“ ../Pynewood/pnw” 
    cli(sys.argv)
  cli中第11行的文件“ /Users/daknok/Desktop/Pynewood/pynewood/cli.py”
    打印(提交)
  __str__中的第14行的“ /Users/daknok/Desktop/Pynewood/pynewood/commit.py”文件
    ''').format(self .__ dict__)
KeyError:“ uid”

当键在字典中明确存在时,为什么会出现此错误?

小智 5

str.format()期望使用kwargs,因此您需要使用扩展字典**

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

    {message}
    ''').format(**self.__dict__)
Run Code Online (Sandbox Code Playgroud)