使用getattr获取祖父母类的属性 [英] Getting an attribute of grandparent class using getattr
问题描述
我试图从ClassB
的实例访问Base
类的实例属性(inst_baseA / inst_baseB
),具体取决于实例(对象ClassB的self.x
)的属性.
I'm trying to access an instance attribute (inst_baseA / inst_baseB
) of Base
class from an instance of ClassB
, depending on an attribute of the instance (self.x
of object ClassB).
这是我的代码:
class Base(object):
def __init__(self):
self.inst_baseA = 'base_B'
self.inst_baseB = 'base_A'
class ClassA(object):
def __init__(self):
self.node = Base()
class ClassB(ClassA):
def __init__(self):
super(ClassB, self).__init__()
self.x = 'base_A'
这是我首先尝试的:
>>> b = ClassB()
>>> getattr(b, 'node.inst_{}'.format(b.x))
Traceback (most recent call last):
File "<pyshell#26>", line 1, in <module>
getattr(b, 'node.inst_{}'.format(b.x))
AttributeError: 'ClassB' object has no attribute 'node.inst_base_A'
如果我将调用链接到getattr,我将克服这个问题:
I overcome this if I chain calls to getattr:
>>> getattr(getattr(b, 'node'), b.x)
'base_A'
出于好奇:除了对getattr
进行两次调用之外,是否有其他方法可以从孙辈类中获取Base类的属性?
Out of curiosity: Is there a way to get an attribute of the Base class from grandchildren class besides doing two calls to getattr
?
更新:我需要它的原因是我正在尝试: -从祖父母类获取属性(inst_baseA或inst_baseB) -取决于实例的属性(x的值)
Update: the reason I need it is I'm trying to: - Get an attribute fron grandparent class (either inst_baseA or inst_baseB) - Depending on an attribute on my instance (the value of x)
所以我的代码实际上是这样的:getattr(self, 'node.{}'.format(self.x))
.第一次我没有正确地解释它,希望现在更有意义.
So my code is actually something like: getattr(self, 'node.{}'.format(self.x))
. I didn't explain it correctly at the first time, hope it makes more sense now.
推荐答案
There's operator.attrgetter
, but it's really not meant for this kind of thing, so the syntax is pretty awkward:
>>> operator.attrgetter('node.inst_base')(b)
'base'
但这确实是很不直观的,因此,为了避免使阅读您的代码的人感到困惑,最好改用自己的多getattr:
But this is really quite unintuitive, so to avoid confusing people who read your code, it's probably better to roll your own multi-getattr instead:
def get_multi_attr(obj, attrs):
for attr in attrs.split('.'):
obj = getattr(obj, attr)
return obj
>>> get_multi_attr(b, 'node.inst_base')
'base'
这篇关于使用getattr获取祖父母类的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!