【发布时间】:2012-07-21 10:21:46
【问题描述】:
我有一堂课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。
回溯(最近一次通话最后): 文件“../Pynewood/pnw”,第 7 行,在 cli(sys.argv) 文件“/Users/daknok/Desktop/Pynewood/pynewood/cli.py”,第 11 行,在 cli 打印(提交) 文件“/Users/daknok/Desktop/Pynewood/pynewood/commit.py”,第 14 行,在 __str__ ''').format(self.__dict__) 键错误:'uid'
为什么我得到这个错误,而字典中显然存在键?
【问题讨论】:
-
您也可以使用
vars(self)。我认为它看起来比self.__dict__
标签: python dictionary python-3.x