Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get the same class variable of a list of class instances of the same class?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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))

?

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading