Python-getattr和串联 [英] Python - getattr and concatenation

查看:49
本文介绍了Python-getattr和串联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,在我的代码中使用getattr时,我发现了以下内容:

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

返回一个错误,指示foo不包含属性A.bar.我要去哪里错了?谢谢!

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

推荐答案

因为foo上没有属性A.bar.属性barA指向的对象的一部分,对象是foo的属性.您需要

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

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

这篇关于Python-getattr和串联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆