如何将对象的选定属性放入 python 列表?

How to get selected attributes of an object in to a python list?

如何使用 python 中对象的选定属性创建列表?使用列表理解。

例如:

我的对象A有

A.name
A.age
A.height

以及更多属性

如何创建列表[name,age]

我可以手动完成,但它看起来很难看:

l=[]
l.append(A.name)
l.append(A.age)

但我正在寻找捷径。

您要找的是operator.attrgetter

attrs = ['name', 'age'] 
l = list(operator.attrgetter(*attrs)(A))

为什么不 [A.name, A.age]list 文字很简单。 You could use operator.attrgetter if you need to do it a lot,虽然它在获取多个属性时 returns tuples,而不是 lists,所以如果你不能接受它,你就必须转换。

您可以通过所有 A class 属性收集它们并检查它们是不是方法还是内置。

import inspect

def collect_props():
    for name in dir(A):
        if not inspect.ismethod(getattr(A, name)) and\
           not name.startswith('__'):
            yield name

print list(collect_props())