给定一个具有属性a和b的对象列表,我想从列表中满足给定约束的第一个对象获取属性。下面显示了一种解决方案,但对于具有许多属性的对象,这是不可取的。你知道吗
class Foo(object):
def __init__(self):
self.a = 0
self.b = 1
def get_first_a(l):
return next(val.a for val in l if val.a > 0)
def get_first_b(l):
return next(val.b for val in l if val.b > 0)
def main():
bar0 = Foo()
bar1 = Foo()
bar2 = Foo()
bar2.a = 10
l = [bar0, bar1, bar2]
a = get_first_a(l) # returns 10
b = get_first_b(l) # returns 1
有没有办法将对象属性传递给函数?我不希望添加枚举或使用字符串匹配,而是希望使用以下内容:
def get_first_b(l, object_attribute):
return next(val.object_attribute for val in l if val.object_attribute != 0)
您可以使用getattr,但如果没有符合您条件的object\u属性,则最终会出现StopIteration错误:
您可以将所需的内容传递给单个函数:
输出:
使用
getattr
为任何属性定义一个函数如果您知道对象中的属性,请尝试以下操作:
相关问题 更多 >
编程相关推荐