我想构建一个类,它基本上是一个对象数组。我希望此类返回其成员的属性列表。例如,来自类(class):
class Animal():
def __init__(self, height, age):
self.height = height
self.age = age
dog = Animal(1,2)
cat = Animal(3,4)
我想创建一个类组,它可以:
my_group = Group([dog,cat])
print(my_group.height) #return [1,3] or (1,3) or array([1,3])
我想过这样做:
import inspect
def get_attribute(instance):
"""Return all attributes of an instance (except all internal built-in)"""
attributes = inspect.getmembers(instance, lambda a:not(inspect.isroutine(a)))
return [a for a in attributes if not(a[0].startswith('__') and a[0].endswith('__'))]
class Group():
def __init__(self, members):
self.members = members
attributes = [a[0] for a in get_attribute(list(members)[0])] #assuming members are all of the same class
for a in attributes:
setattr(self, a, [getattr(m, a) for m in self.members])
然后我可以将 Group 用于其他类,例如:
class Human():
def __init__(self, name, weight):
self.name = name
self.weight = weight
class Family(Group):
pass
alan = Human("alan", 1)
bob = Human("bob", 2)
my_family = Family([alan, bob])
print(my_family.weight) #returns [1, 2]
这可行,但如果成员数量变得非常多,则似乎效率低下,因为它会循环每个成员。基本上,我的代码可以工作,但我想使用 map 或类似的功能使其更快。
最佳答案
使用类属性:
class Animal():
all_data = {"height":[],"age":[]}
def __init__(self, height, age):
self.height = height
self.age = age
Animal.all_data["age"].append(age)
Animal.all_data["height"].append(height)
dog = Animal(1,2)
cat = Animal(3,4)
print(Animal.all_data["height"])
print(Animal.all_data["age"])
关于python - 使用类访问对象列表的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35116538/