getting dynamic attribute in python [duplicate]

自古美人都是妖i 提交于 2019-11-27 22:48:46

How about:

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

This has the advantage of working with any number of items:

 def getfirstattr(obj, *attrs):
     return next((getattr(obj, attr) for attr in attrs 
                  if hasattr(obj, attr)), None)

This does have the very minor drawback that it does two lookups on the final value: once to check that the attribute exists, another to actually get the value. This can be avoided by using a nested generator expression:

 def getfirstattr(obj, *attrs):
     return next((val for val in (getattr(obj, attr, None) for attr in attrs)
                  if val is not None), None)

But I don't really feel it's a big deal. The generator expression is probably going to be faster than a plain old loop even with the double-lookup.

I think using dir will get u essentially the same thing __dict__ normally does ...

targetValue = "value"
for k in dir(obj):
    if getattr(obj,k) == targetValue:
       print "%s=%s"%(k,targetValue)

something like

>>> class x:
...    a = "value"
...
>>> dir(x)
['__doc__', '__module__', 'a']
>>> X = x()
>>> dir(X)
['__doc__', '__module__', 'a']
>>> for k in dir(X):
...     if getattr(X,k) == "value":
...        print "%s=%s"%(k,getattr(X,k))
...
a=value
>>>

There may be a better way to do this depending on the structure of your object, but knowing nothing else, here is a recursive solution that works exactly like your current solution except that it will work with an arbitrary number of arguments:

g = lambda o, l: getattr(o, l[0], g(o, l[1:])) if l else None

And another one:

reduce(lambda x, y:x or  getattr(obj, y, None),  "a b c".split(), None)

(in Python 3 you have to import reduce from functools. It is a builtin in Python 2)

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!