在python中获取动态属性 [英] getting dynamic attribute in python
问题描述
我有一个带有 pseudo 或 special 属性的对象,该属性可以用三种不同的方式命名(注意:我不控制生成该对象的代码)
I have and object with an pseudo or special attribute that can be named in three different ways (Note: I don't control the code which generates the object)
属性中的值(取决于设置的是哪个)是完全相同的,我需要获取该值以进行进一步处理,因此根据数据源,我可以得到类似以下内容的东西:
The value in the attributes (depending which one is set) is exactly the same, and I need to get that for further processing, so depending of the source of data, I can have something like:
>>> 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
调用.假设可能性只有三种,则代码如下所示:
I'm interested in getting 'value'
and unfortunately __dict__
property does not exist in that object. So what I ended doing for getting that value was just do a bunch of getattr
calls. Assuming that possibilities are only three, the code looked like this:
>>> g = lambda o, l: getattr(o, l[0], getattr(o, l[1], getattr(o, l[2], None)))
>>> g(obj, ('a', 'b', 'c'))
'value'
现在,我想知道是否有更好的方法?当我100%相信自己所做的事情时:)
Now, I would like to know whether there is a better way to this? As I'm 100% convinced what I've done :)
预先感谢
推荐答案
怎么样:
for name in 'a', 'b', 'c':
try:
thing = getattr(obj, name)
except AttributeError:
pass
else:
break
这篇关于在python中获取动态属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!