【问题标题】:python getattr() with multiple paramspython getattr() 具有多个参数
【发布时间】:2017-03-05 08:34:00
【问题描述】:

构造getattr(obj, 'attr1.attr2', None) 不起作用。 替换这种结构的最佳做法是什么? 把它分成两个 getattr 语句?

【问题讨论】:

标签: python python-3.x getattr


【解决方案1】:

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

from operator import attrgetter

my_attrs = attrgetter(attr1, attr2)(obj)

【讨论】:

  • 我认为 OP 想要my_attrs = ('attr1.attr2')(obj)
  • 标题说的有些不同。
  • @elena 是的,这个标题使这个模棱两可。
  • 对不起。我想使用 getattr 或其他方法获取obj.attr1.attr2
【解决方案2】:

this answer 中所述,最直接的解决方案是使用operator.attrgetter(更多信息请参见this python docs page)。

如果由于某种原因,此解决方案不能让您满意,您可以使用以下代码 sn-p:

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,它确实有效。我测试并使用了它。

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

      【解决方案4】:

      获得多个属性的一种简单但不是很有说服力的方法是使用带或不带括号的元组,例如

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

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

      getattr(myObj.contained, "c")
      

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-03-24
        • 2021-09-10
        • 2018-04-03
        • 2019-03-28
        • 2019-07-18
        • 1970-01-01
        • 2022-11-28
        • 1970-01-01
        相关资源
        最近更新 更多