Search code examples
pythonclassoopattributesinstances

How to access the attributes of all instances stored in a list?


Intro

Comming from this question

Python- creating object instances in a loop with independent handling

I was asking myself how to access the attributes of all rather than just a single instance, if you have created a list of instances.

Minimal Example

Consider creating a list of company instances with the attributes name and value. Now I would like to know, which of these companies does have the highest value.

So far I am simply storing the values of the value attribute in an array and then find the index of the maximum value.

import numpy as np

class Company(object):
    def __init__(self, name, value):
        self.name = name
        self.value = value

companies = []
for name in 'ABC':
    companies.append(Company(name, np.random.rand()))

l = len(companies)
liste = np.zeros(l)
for i in range(l):
    liste[i] = companies[i].value

ind = np.unravel_index(np.argmax(liste), liste.shape)
print("Highest value: ", liste[ind])
print("Company of highest value: ", companies[ind[0]].name)

Questions

1) Is there a different way to create this list of all attribute values without a for-loop?

2) Is there a direct way to find the instance in a list, for which the value of a certain attribute is maximal?


Solution

  • It doesn't avoid for completely but replaces it with list comprehension:

    from operator import attrgetter
    
    max_val_company = max((c for c in companies), key=attrgetter('value'))
    

    max_val_company will contain Company object having max value attribule.