Python - getattr and concatenation

笑着哭i 提交于 2020-02-14 00:58:34

问题


So in playing around with getattr in my code I discovered the following:

myVariable = foo.A.bar

works...but something like this:

B = "A"
myVariable = getattr(foo, B + ".bar")

returns an error that foo does not contain an attribute A.bar. Where am I going wrong? Thanks!


回答1:


Because there is no attribute A.bar on foo. Attribute bar is a part of the object pointed to by A, which is an attribute of foo. You need either

getattr(foo.A, "bar")

or

getattr(getattr(foo, 'A'), 'bar')

The generic code for accessing deep attributes is to split on the dot, and go until the last part is found (I'm writing from memory, not tested):

def getattr_deep(start, attr):
    obj = start
    for part in attr.split('.'):
        obj = getattr(obj, part)
    return obj

getattr_deep(foo, 'A.bar')



回答2:


The equivalent of :

myVariable = foo.A.bar 

using getattr would take 2 steps.

aObject = getattr(foo, 'A') 
myVariable = getattr(aobject, 'bar')

doing it in your way `myVariable = getattr(foo, B + ".bar") means 'myVariable = getattr(foo, "B.bar")' getAttr now lookups the string "B.bar" which obviously does not exist.



来源:https://stackoverflow.com/questions/7778867/python-getattr-and-concatenation

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