python 具有多个参数的 getattr()

python getattr() with multiple params

建筑getattr(obj, 'attr1.attr2', None)不工作。 替换此结构的最佳做法是什么? 将其分成两个 getattr 语句?

您可以使用 operator.attrgetter() 来一次获取多个属性:

from operator import attrgetter

my_attrs = attrgetter(attr1, attr2)(obj)

this answer, the most straightforward solution would be to use operator.attrgetter (more info in this python docs page)所述。

如果出于某种原因,此解决方案无法让您满意,您可以使用此代码段:

def multi_getattr(obj, attr, default = None):
"""
Get a named attribute from an object; multi_getattr(x, 'a.b.c.d') is
equivalent to x.a.b.c.d. When a default argument is given, it is
returned when any attribute in the chain doesn't exist; without
it, an exception is raised when a missing attribute is encountered.

"""
attributes = attr.split(".")
for i in attributes:
    try:
        obj = getattr(obj, i)
    except AttributeError:
        if default:
            return default
        else:
            raise
return obj

# Example usage
obj  = [1,2,3]
attr = "append.__doc__.capitalize.__doc__"

multi_getattr(obj, attr) #Will return the docstring for the
                         #capitalize method of the builtin string
                         #object

来自 this page,这确实有效。我测试并使用它。

如果您有想要在列表中获取的属性名称,您可以执行以下操作:

my_attrs = [getattr(obj, attr) for attr in attr_list]

一种简单但不是很 eloquent 的方式来获得多个 attr 是使用带或不带括号的元组,例如

aval, bval =  getattr(myObj,"a"), getattr(myObj,"b")

但我认为您可能希望通过使用点表示法的方式获取包含的对象的属性。在这种情况下,它将类似于

getattr(myObj.contained, "c")

其中 contained 是包含在 myObj 对象中的对象,c 是 contained 的属性。如果这不是您想要的,请告诉我。