在python中获取动态属性

rho*_*aza 18 python getattr

我有一个特殊属性的对象,可以用三种不同的方式命名(注意:我不控制生成对象的代码)

属性中的值(取决于哪一个)是完全相同的,我需要得到它以进行进一步处理,因此根据数据源,我可以有类似的东西:

>>> obj.a
'value'
>>> obj.b
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: Obj instance has no attribute 'b'
>>> obj.c
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: Obj instance has no attribute 'c'
Run Code Online (Sandbox Code Playgroud)

要么

>>> obj.a
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: Obj instance has no attribute 'a'
>>> obj.b
'value'
>>> obj.c
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: Obj instance has no attribute 'c'
Run Code Online (Sandbox Code Playgroud)

要么

>>> obj.a
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: Obj instance has no attribute 'a'
>>> obj.b
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: Obj instance has no attribute 'b'
 >>> obj.c
'value'
Run Code Online (Sandbox Code Playgroud)

我很感兴趣,'value'不幸的__dict__是,该物品中不存在物业.所以我为获得这个价值所做的就是做一堆getattr电话.假设可能性只有三个,代码看起来像这样:

>>> g = lambda o, l: getattr(o, l[0], getattr(o, l[1], getattr(o, l[2], None)))
>>> g(obj, ('a', 'b', 'c'))
'value'
Run Code Online (Sandbox Code Playgroud)

现在,我想知道是否有更好的方法呢?因为我100%确信我做了什么:)

提前致谢

wim*_*wim 39

怎么样:

for name in 'a', 'b', 'c':
    try:
        thing = getattr(obj, name)
    except AttributeError:
        pass
    else:
        break
Run Code Online (Sandbox Code Playgroud)