Home > Back-end >  How to get the same class variable of a list of class instances of the same class?
How to get the same class variable of a list of class instances of the same class?

Time:01-03

I have a class which has some class variables, methods, etc. Let's call it Cell.

class Cell:
    def __init__(self):
        self.status = 0
        ...

I have a list of different instances of this class.

grid = [Cell.Cell() for i in range(x_size*y_size)]

Is it possible to get the upper shown status variable of each of the instances stored in grid in a vectorized manner without looping through the elements of the list?

CodePudding user response:

Not in vanilla Python.

statuses = [x.status for x in grid]

If you are looking for something that abstracts away the explicit iteration, or even just the for keyword, perhaps you'd prefer

from operator import attrgetter

statuses = list(map(attrgetter('status'), grid))

?

  • Related