简体   繁体   English

如何通过 python 中的属性获取所有 class 对象

[英]How to get all the class objects by attributes in python

I have a list of objects representing rooms in a building, each object has attributes like area, category etc. I know i can use sort() to sort the list by a specific attribute, but how would I go around sorting objects by a specific attribute and create separate lists containing objects with the same value in the attribute?我有一个代表建筑物中房间的对象列表,每个 object 都具有区域、类别等属性。我知道我可以使用 sort() 按特定属性对列表进行排序,但是我将如何 go 围绕特定的对象排序属性并创建包含在属性中具有相同值的对象的单独列表? For example one list with all the objects with category attribute = "private" and another with "public" etc例如,一个列表包含所有具有类别属性 =“private”的对象,另一个包含“public”等

This would work.这会奏效。

private_List = []
for obj in List:
    if hasattr(obj, "private"):
        private_List.append(obj)

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

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