0

我在一个包含整数作为值的类上有许多属性。根据用户当前的选择,给定属性的所有数据可能为零,在这种情况下我不想显示它。

我正在尝试定义一个函数来检查每个属性:

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'

显然“属性”没有被传递给college.attribute,而是被字面理解为“属性”属性。有没有办法做到这一点?

4

1 回答 1

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'

I should say, though, that I seldom use getattr and setattr myself. Whenever you need to apply something to many attributes at once, you realize you need to put their names somewhere so you can loop over them.. and if you're doing that, you might as well use a dict to start with!

于 2013-03-30T04:20:16.043 回答