我拥有和object的伪或特殊属性,可以用三种不同的方式命名(注意:我不控制生成对象的代码)
属性中的值(取决于设置的属性)完全相同,我需要获取该值以进行进一步处理,因此根据数据源的不同,我可以拥有如下内容:>>> obj.a
'value'
>>> obj.b
Traceback (most recent call last):
File "", line 1, in
AttributeError: Obj instance has no attribute 'b'
>>> obj.c
Traceback (most recent call last):
File "", line 1, in
AttributeError: Obj instance has no attribute 'c'
或者>>> obj.a
Traceback (most recent call last):
File "", line 1, in
AttributeError: Obj instance has no attribute 'a'
>>> obj.b
'value'
>>> obj.c
Traceback (most recent call last):
File "", line 1, in
AttributeError: Obj instance has no attribute 'c'
或者>>> obj.a
Traceback (most recent call last):
File "", line 1, in
AttributeError: Obj instance has no attribute 'a'
>>> obj.b
Traceback (most recent call last):
File "", line 1, in
AttributeError: Obj instance has no attribute 'b'
>>> obj.c
'value'
我对获取'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'
现在,我想知道是否有更好的方法?因为我百分之百确信我所做的:)
提前谢谢