def class ObjClass:
attr1;
attr2;
attr3;
attr4;
attr5;
def __init__(self):
print("Some logic goes here")
在另一个.py文件中
obj1 = obj.objClass();
obj1.attr1 = foo
obj1.attr2 = bar (..... so on and so forth)
objList = []
objList.append(obj1)
objList.append(obj2)
objList.append(obj3)
objList.append(obj4)
objList.append(obj5)
现在列表中的所有对象,我想将具有相同attr1,attr2,attr3但不同attr4和attr5的对象分组。我该怎么做?
这样做的pythonic方法是什么?我知道如何使用列表但不使用对象。
答案 0 :(得分:0)
def grouper(objs, attr_name):
group =[]
for obj in objs:
if hasattr(obj, attr_name):
group.append(obj)
return group
返回一个对象列表 - 您选择的属性等于您想要的值。