我有一个类“CocoPart”,它是这样定义的:

class CocoPart(Enum):
    Wrist = 4
    LShoulder = 5
    LElbow = 6
    LWrist = 7
    RHip = 8
    RKnee = 9
    RAnkle = 10
    LHip = 11
    LKnee = 12
    LAnkle = 13
    REye = 14
    LEye = 15
    REar = 16
    LEar = 17
    Background = 18

这些成员被进一步操纵。在程序的后面,我需要用他们的名字访问他们。我该怎么做?

最佳答案

您可以通过多种方式访问成员。

>>> list(CocoPart)
[<CocoPart.Wrist: 4>, ...]

>>> CocoPart.__members__.items()
odict_items([('Wrist', <CocoPart.Wrist: 4>), ...])

>>> for name, member in CocoPart.__members__.items():
...     print(name, member.value)
...
Wrist 4
LShoulder 5
...

你可以找到更多的细节here

关于python - 如何使用枚举键访问和打印类的成员?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56465228/

10-10 19:32