[英]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:我想要一个枚举器 class ,它具有具有相同值的 class 变量,例如:
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:现在我想遍历 Cars class 并获取每辆车的字符串值:
for car in Cars:
print(car)
gives output:给出 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
但我不想用.value
迭代
i tried to implement __iter__()
and __next__()
methods but couldn't achieve it.我试图实现__iter__()
和__next__()
方法但无法实现。
You can do this by overriding __str__
:您可以通过覆盖__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.只需将 colors 用作它们的对象,并在需要时调用.value
。 Better yet you can just use .name
:更好的是,您可以使用.name
:
from enum import auto, Enum
class Cars(Enum):
BMW = auto()
Audi = auto()
for brand in Cars:
print(brand.name)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.