如何忽略Python对象中未定义的属性?

2024-10-01 07:47:39 发布

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

我有一个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()和{}来解决我的问题。谢谢大家的建议。在


Tags: 标记self程序脚本名称return字典属性
3条回答

是的,您可以查询对象,并迭代地构建dict:

for prop in ('dclabels', 'tdclabels'):
    try:
        sheets[prop] = getattr(self, prop)
    except AttributeError: pass # expected

(样式注释:PEP8样式永远不会将代码放在冒号后面的一行;我发现将一个语句的套件放在冒号的同一行上更具可读性,只要所有代码和任何相关注释都很短)

你可以这样做:

sheets = { }
attr = getattr(self, "dclabels", None)
if attr is not None:
    sheets["dclabels"] = attr

或者像这样:

^{pr2}$

在使用变量之前,必须声明变量:

class ClassName(object):
    __init__(self,dclabels=None, tdlabels=None):
         self.dclabels = dclabels
         self.tdlabels = tdlabels

相关问题 更多 >