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!