2016-09-28 118 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