获取属性python

时间:2016-09-28 03:49:03

标签: python python-2.7

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

有没有办法获得这些? 任何帮助都会得到满足,谢谢。

1 个答案:

答案 0 :(得分: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)