class A(object):
a = 1
b = 0
c = None
d = None
a_obj=A()
a_list = ['a', 'b', 'c', 'd']
attrs_present = filter(lambda x: getattr(a_obj, x), a_list)
我想要a和b属性,这里0是有效值。我不想使用比较== 0
有没有办法获得这些? 任何帮助都会得到满足,谢谢。
答案 0 :(得分:2)
如果您要排除c
,d
(None
s),请使用is None
或is not None
:
attrs_present = filter(lambda x: getattr(a_obj, x, None) is not None, a_list)
# NOTE: Added the third argument `None`
# to prevent `AttributeError` in case of missing attribute
# (for example, a_list = ['a', 'e'])
如果您想加入c
,d
,请使用hasattr
:
attrs_present = filter(lambda x: hasattr(a_obj, x), a_list)