gpt4 book ai didi

python - 当 key 明显存在时,为什么我会收到 KeyError?

转载 作者:太空宇宙 更新时间:2023-11-03 13:03:31 29 4
gpt4 key购买 nike

我有一个类 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__)

这对我来说似乎是对的;从 print 调用的输出中可以看出,两个键都存在并且都不是None:

{'message': 'Hello, world!', 'uid': 1}

但是,在列表行调用 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'

为什么我会收到此错误,而键显然存在于字典中?

最佳答案

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

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

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

关于python - 当 key 明显存在时,为什么我会收到 KeyError?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11591348/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com