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

python iterate over class variables and only get values of variables

i want an enumerator class which has class variables with same values such as:

from enum import Enum
class Cars(Enum):
  BMW = "BMW"
  Mercedes = "Mercedes"
  Renault = "Renault"

Now i want to iterate over Cars class and get string values of each car as:

for car in Cars:
  print(car)

gives output:

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

Cars.BMW
Cars.Mercedes
Cars.Renault

to get only string values i need to do:

for car in Cars:
  print(car.value)

But i dont want iterate with.value

i tried to implement __iter__() and __next__() methods but couldn’t achieve it.

>Solution :

You can do this by overriding __str__:

from enum import Enum


class Cars(Enum):
    BMW = "BMW"
    Audi = "Audi"

    def __str__(self):
        return self.value

This isn’t really how enum’s should be used, though, so I wouldn’t recommend it. Just use the colors as the objects they are, and call on .value when you need it. Better yet you can just use .name:

from enum import auto, Enum


class Cars(Enum):
    BMW = auto()
    Audi = auto()


for brand in Cars:
    print(brand.name)
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