How to access and print the members of a class using the enumeration key?

Viewed 61

I have a class 'CocoPart' and it is defined this way:

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

These members are further manipulated. Later in the program, I need to access them using their name. How can I do it?

2 Answers

You can access the members in multiple ways.

>>> 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
...

You can find more details here.

You have two options for name access:

CocoPart.Wrist  # when you know at programming time

enum_name = 'Wrist'
CocoPart[enum_name]  # when the name is stored in a variable
Related