我已经和与伪或特殊属性,可以在三种不同的方式来命名对象(注:我不控制它生成对象的代码)越来越动态属性在Python
的(取决于哪一个设置)中的属性值是完全一样的,我需要得到进一步的处理,所以要根据数据的来源,我可以有这样的:
>>> 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'
或
>>> 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'
或
>>> 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'
我感兴趣的是得到'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'
现在,我想知道是否有这更好的办法?正如我100%相信我做了什么:)提前
感谢
只是为了检查 - 没有一个'get_value()'(或类似的),或者你提到'取决于数据源' - 没有现有的(或可导出的映射)源 - >属性名称? –