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