2016-09-28 117 views
3
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获取属性python

有没有办法得到那些? 任何帮助将appriciated,谢谢。

回答

2

如果你想排除cdNone S),使用is Noneis 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']) 

如果你想包括cd,使用hasattr

attrs_present = filter(lambda x: hasattr(a_obj, x), a_list) 
+1

感谢@falsetru 。 –

+1

您可以通过将其标记为答案来更多地感谢他们。 ;) – haliphax