简体   繁体   English

如何在python列表中获取对象的选定属性?

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

How do I create a list with the selected attributes of an object in python ? 如何使用python中对象的选定属性创建列表? Using list comprehensions. 使用列表推导。

Eg: 例如:

My object A has 我的对象A有

A.name
A.age
A.height

and many more attributes 还有更多属性

How do I create a list [name,age] 如何创建列表[name,age]

I can do it manually but it looks ugly: 我可以手动完成,但看起来很丑:

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

but I am looking for a shortcut. 但我正在寻找捷径。

Why not just [A.name, A.age] ? 为什么不只是[A.name, A.age] list literals are simple. list文字很简单。 You could use operator.attrgetter if you need to do it a lot , though it returns tuple s when fetching multiple attributes, not list s, so you'd have to convert if you can't live with that. 如果需要做很多事可以使用operator.attrgetter ,尽管它在获取多个属性而不是list时会返回tuple s,所以如果不能使用它,则必须进行转换。

What you're looking for is operator.attrgetter 您正在寻找的是operator.attrgetter

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

You can collect them going through all A class attributes and checking if they aren't method or built-in. 您可以通过所有A类属性来收集它们,并检查它们不是方法还是内置的。

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())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM