![](/img/trans.png)
[英]How to access a class object inside a list when a value for one of the class attributes is given in Python?
[英]Access attributes of a list of object using class
我想建立一个基本上是对象数组的类。 我希望该类向我返回其成员的属性列表。 例如,从类中:
class Animal():
def __init__(self, height, age):
self.height = height
self.age = age
dog = Animal(1,2)
cat = Animal(3,4)
我想创建一个类Group来做:
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属性:
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"])
也许您可以定义一个方法使其保持动态:
class Animal():
def __init__(self, height, age):
self.height = height
self.age = age
dog = Animal(1,2)
cat = Animal(3,4)
class Group():
def __init__(self, members):
self.members = members
def get_all_attr(self, a):
return [getattr(m,a) for m in self.members]
my_group = Group([dog,cat])
print(my_group.get_all_attr("height")) #returns [1,3]
我认为除非每次使用懒惰初始化,否则您都无法避免不遍历成员。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.