如何为Python对象创建一个孤立的属性列表?

huangapple go评论55阅读模式
英文:

How to create an isolated list of attributes for a python object?

问题

我有一个名为my_obj的Python对象,它有许多称为*attr1,attr2,attr3,...*的属性。这些属性表示为字符串

我想按照以下模式创建这些属性的列表:

attr_list = [my_obj.attr1, my_obj.attr2, my_obj.attr3]

其中列表的每个元素都是一个对象,而不是一个字符串使用一个循环,在循环中逐个添加元素

在将它们连续附加到列表之前,我不知道如何将字符串转换为对象。

非常感谢你的帮助。

英文:

I have a python object called my_obj that has many attributes called attr1, attr2, attr3, .... represented as strings.

I would like to create a list of these attributes in the following pattern:

attr_list = [my_obj.attr1, my_obj.attr2, my_obj.attr3]

where each element of the list is an object rather than a string using a for loop in which elements are added one at a time.

I don't know how to convert strings into object before appending them to the list consecutively.

Your help is greatly appreciated.

答案1

得分: 1

有一个内置函数可以在Python 3中满足您的需求:getattr

官方文档在此

返回对象的命名属性的值。name必须是一个字符串。如果字符串是对象属性之一的名称,则结果是该属性的值。

我们可以使用getattr来解决您的问题:

attr_names = ["attr1", "attr2", "attr3"]
attr_list = []

for name in attr_names:
    attr = getattr(my_obj, name)
    attr_list.append(attr)
英文:

There is a built-in function that does what you need, off-the-shelf, in Python 3: getattr

Official doc here

> Return the value of the named attribute of object. name must be a
> string. If the string is the name of one of the object’s attributes,
> the result is the value of that attribute.

We could use getattr this way to tackle your problem:

attr_names = ["attr1", "attr2", "attr3"]
attr_list = []

for name in attr_names:
    attr = getattr(my_obj, name)
    attr_list.append(attr)

答案2

得分: 1

更清晰的方式可能是:

attr_list = [getattr(my_obj, name) for name in attr_names]
英文:

a cleaner way could be

attr_list=[getattr(my_obj,name)for name in attr_names]

huangapple
  • 本文由 发表于 2023年7月11日 01:17:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/76655956.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定