python - 使用类访问对象列表的属性

标签 python arrays object metaclass

我想构建一个类,它基本上是一个对象数组。我希望此类返回其成员的属性列表。例如,来自类(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/

相关文章:

Python - 零阶保持插值(最近邻)

Javascript 对象代码数组

c++ - 另一个 C++ 池球对象数组问题

javascript - JavaScript 中数组是对象吗?

Python 认为 Euler 存在身份问题(cmath 返回奇怪的结果)

python - 转换或去除 "illegal"Unicode 字符

python - np.partition() 如何解释参数 kth?

java - 如何在 Java 中返回一个临时的 int 数组

c++ - 从友元函数中的对象访问成员函数

python - 有条件地在多个索引上加入 pandas DF