Python - getattr and concatenation

此生再无相见时 提交于 2019-12-01 00:26:11

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')

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.

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