我有一个Python字典,它将键名称标记为属性。绑定到这个字典的程序被设置为只有几个项,并且只有在必要时才有。所以,并不是每次脚本运行时都定义字典中的所有属性。在
这是字典里的代码
def getWidths(self,sheetName):
sheets = {
'dclabels':self.dclabels,
'tdclabels':self.tdclabels
}
sheetName = sheetName.lower()
if sheetName in sheets:
return sheets.get(sheetName)
else:
return self.colWidths
我收到一个错误声明AttributError: ClassName instance has no attribute 'dclabels'
如何避免这个错误?有没有办法让脚本忽略任何未定义的属性?谢谢!在
我找到了解决问题的办法。在
^{pr2}$我使用hasattr()
和{
是的,您可以查询对象,并迭代地构建dict:
(样式注释:PEP8样式永远不会将代码放在冒号后面的一行;我发现将一个语句的套件放在冒号的同一行上更具可读性,只要所有代码和任何相关注释都很短)
你可以这样做:
或者像这样:
^{pr2}$在使用变量之前,必须声明变量:
相关问题 更多 >
编程相关推荐