如何忽略非';在Python对象中定义了t?
我有一个Python字典,它将键名标记为属性。绑定到此词典的程序被设置为仅包含少数项,并且仅在必要时才包含这些项。因此,并非字典中的所有属性都是在该脚本的每个过程中定义的 这是字典的代码如何忽略非';在Python对象中定义了t?,python,dictionary,Python,Dictionary,我有一个Python字典,它将键名标记为属性。绑定到此词典的程序被设置为仅包含少数项,并且仅在必要时才包含这些项。因此,并非字典中的所有属性都是在该脚本的每个过程中定义的 这是字典的代码 def getWidths(self,sheetName): sheets = { 'dclabels':self.dclabels, 'tdclabels':self.tdclabels } sheetName = sheetName.lower()
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
我在声明attributeError时出错:ClassName实例没有属性“dclabels”
如何避免这个错误?有没有办法让脚本忽略任何未定义的属性?谢谢
我找到了解决我问题的办法
def getWidths(self,sheetName):
if hasattr(self, sheetName.lower()):
name = getattr(self,sheetName.lower())
self.name = name
return self.name
else:
return self.colWidths
我使用了
hasattr()
和getattr()
来解决我的问题。谢谢大家的建议。您可以这样做:
sheets = { }
attr = getattr(self, "dclabels", None)
if attr is not None:
sheets["dclabels"] = attr
try:
sheets["dclabels"] = self.dclabels
except AttributeError:
pass
class ClassName(object):
__init__(self,dclabels=None, tdlabels=None):
self.dclabels = dclabels
self.tdlabels = tdlabels
或者像这样:
sheets = { }
attr = getattr(self, "dclabels", None)
if attr is not None:
sheets["dclabels"] = attr
try:
sheets["dclabels"] = self.dclabels
except AttributeError:
pass
class ClassName(object):
__init__(self,dclabels=None, tdlabels=None):
self.dclabels = dclabels
self.tdlabels = tdlabels
必须先声明变量,然后才能像这样使用它:
sheets = { }
attr = getattr(self, "dclabels", None)
if attr is not None:
sheets["dclabels"] = attr
try:
sheets["dclabels"] = self.dclabels
except AttributeError:
pass
class ClassName(object):
__init__(self,dclabels=None, tdlabels=None):
self.dclabels = dclabels
self.tdlabels = tdlabels
是的,您可以查询您的对象,并以迭代方式构建dict:
for prop in ('dclabels', 'tdclabels'):
try:
sheets[prop] = getattr(self, prop)
except AttributeError: pass # expected
(样式说明:PEP8样式永远不会将代码放在冒号后面的一行;我发现将一组语句放在冒号后面的同一行更具可读性,只要所有代码和任何相关注释都很短。)您可以用
return sheets.get(sheetName.lower(),self.colWidths)替换最后一段
。另请参见:@Marcin,很抱歉您的解决方案在我的案例中无效。它只适用于一种场景,但并不适用于所有场景。无论如何,谢谢您的支持。@amlane86在什么意义上它不起作用?我注意到你对这个主题没有留下任何评论。@Marcin,我发布了我上面使用的代码。如果你愿意,你可以看看,但是简单明了。。。我尝试了一些不同的建议,上面的建议对我来说最有效。我意识到拥有一个字典不是正确的方法,最好只是检查一个属性是否存在,而不是遍历一个可能有无数属性的字典来找到一个。getattr()
为我这样做,而无需我定义硬编码项的字典。prop
未定义。我猜你的意思是attr
?@Constantinius谢谢,这个错误是由另一个编辑我答案的用户引入的。@Mike Graham你为什么选择在我的代码中引入错误?根本没有必要编辑迭代变量。@Marcin,撇开我的错误不谈,很明显,许多人最终对Python中术语“属性”的含义感到困惑,因此我认为使用一个更适用的术语,如“属性”,可能会对您更有帮助提高技术交流的透明度。请注意,hasattr
被打破,因为它将使任何异常(而不仅仅是适当的异常)静音。(例如,如果您在错误的时刻点击^C,它将被吞没。)如果坚持这样做,他们应该使用类似于的东西,如果getattr(self,“dclabels”,None)为None:
(或者如果None
为有效值,则使用其他唯一值。)