想象一下,有两个派生自 Enum
的类。 ,例如
class Color(Enum):
blue = 'blue'
red = 'red'
class Properties(Enum):
height = 'h'
weight = 'w'
colors = Color
什么是(可能递归地)迭代嵌套枚举的所有枚举标签的最佳方法,例如
Properties
,包括 Enum
的那些-成员(member)喜欢Properties.colors
在上面的例子中(即包括 Color.blue
和 Color.red
)?检查值的类型?
最佳答案
这是一个简单的示例,它只是将它们打印出来。我将把它作为练习留给读者,以使其成为通用生成器或适用于实际用例的任何内容。 :)
>>> from typing import Type
>>> def print_enum(e: Type[Enum]) -> None:
... for p in e:
... try:
... assert(issubclass(p.value, Enum))
... print_enum(p.value)
... except (AssertionError, TypeError):
... print(p)
...
>>> print_enum(Properties)
Properties.height
Properties.weight
Color.blue
Color.red
关于python - 如何迭代枚举的所有值,包括任何嵌套的枚举?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62090541/