将属性作为参数传递

时间:2013-03-30 04:15:48

标签: python-2.7

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

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

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'属性。有没有办法做到这一点?

1 个答案:

答案 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'

但我应该说,我自己很少使用getattrsetattr。每当你需要同时对多个属性应用某些东西时,你意识到你需要将它们的名字放在某处,这样你就可以遍历它们了......如果你这样做,你也可以使用dict来启动它们。与!