我在类上有许多属性,包含整数作为值。根据用户的当前选择,给定属性的所有数据可能等于零,在这种情况下我不想显示它。
我正在尝试定义一个检查每个属性的函数:
def NoneCheck(collegelist, attribute):
e = []
for college in collegelist:
e.append(int(college.attribute))
if sum(e) == 0:
attribute = False
else:
attribute = True
return attribute
但我最终得到了错误:
'Inventories' object has no attribute 'attribute'
显然'attribute'没有被传递给college.attribute,而是被字面上理解为'attribute'属性。有没有办法做到这一点?
答案 0 :(得分:0)
IIUC,您希望getattr
[docs]从其名称中获取属性。例如:
def NoneCheck(collegelist, attribute):
return sum(getattr(coll, attribute) for coll in collegelist) != 0
给出
>>> NoneCheck([Inventory(0), Inventory(0)], 'book')
False
>>> NoneCheck([Inventory(0), Inventory(4)], 'book')
True
>>> NoneCheck([Inventory(0), Inventory(4)], 'undefined')
Traceback (most recent call last):
File "<ipython-input-5-4aae80aba985>", line 1, in <module>
NoneCheck([Inventory(0), Inventory(4)], 'undefined')
File "<ipython-input-1-424558a8260f>", line 2, in NoneCheck
return sum(getattr(coll, attribute) for coll in collegelist) == 0
File "<ipython-input-1-424558a8260f>", line 2, in <genexpr>
return sum(getattr(coll, attribute) for coll in collegelist) == 0
AttributeError: 'Inventory' object has no attribute 'undefined'
但我应该说,我自己很少使用getattr
和setattr
。每当你需要同时对多个属性应用某些东西时,你意识到你需要将它们的名字放在某处,这样你就可以遍历它们了......如果你这样做,你也可以使用dict
来启动它们。与!