简体   繁体   中英

Get Attributes python

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)

I want both a and b attributes, here 0 is a valid value. I don't want to use comparison==0

is there a way to get those? Any help will be appriciated, Thanks.

If you want to exclude c , d ( None s), use is None or 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'])

If you want to include c , d , use hasattr :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM